3

i need to excute this query mongo on dotnet application. the query return many docs.

db.mycollection.aggregate(
[  
    { $match : { tipo:"user_info" } } ,
    {$group: { 
         _id: {userKey: "$userKey", appId:"$appId"} ,
         uniqueIds: {$addToSet: "$_id"},
         count: {$sum: 1}
        }
        },
    {$match: { 
        count: {"$gt": 1}
        }
    }
]);

i tried this but it returns 0 docs.

var result = collection.Aggregate()
            .AppendStage<BsonDocument>
            (
                new BsonDocument { { "$match", new BsonDocument("tipo", "user_info") } }
            )
            .AppendStage<BsonDocument>
            (
                new BsonDocument { { "$group", new BsonDocument("_id", "{userKey: \"$userKey\", appId:\"$appId\"}")
                .Add("uniqueIds", new BsonDocument("$addToSet", "$_id"))
                .Add("count", new BsonDocument("$sum", "1"))} }
            )
            .AppendStage<BsonDocument>
            (
                new BsonDocument { { "$match", new BsonDocument("count", new BsonDocument("$gt", 1)) } }
            ).ToList();

1 Answer 1

1

The problem here is that you have incorrectly defined your _id for $group stage. MongoDB driver interprets it as a string:

{ "$group" : { "_id" : "{userKey: \"$userKey\", appId:\"$appId\"}", "uniqueIds" : { "$addToSet" : "$_id" }

To fix that you can nest another BsonDocument like:

.AppendStage<BsonDocument>
        (
            new BsonDocument { { "$group", new BsonDocument("_id",
                new BsonDocument() { { "userKey", "$userKey" }, { "appId", "$appId" } })
            .Add("uniqueIds", new BsonDocument("$addToSet", "$_id"))
            .Add("count", new BsonDocument("$sum", 1))} }
        )

which will be translated to:

{ "$group" : { "_id" : { "userKey" : "$userKey", "appId" : "$appId" }, "uniqueIds" : { "$addToSet" : "$_id" }
Sign up to request clarification or add additional context in comments.

1 Comment

just change from string to int

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.