Search code examples
c#.netmongodbaggregation-frameworkmongodb-.net-driver

execute mongo aggregation query using dotnet driver


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();

Solution

  • 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" }