Search code examples
c#mongodbmongodb-.net-driver

MongoDB Aggregate function to C#


this has been bugging me all night.

I have the following MongoDb function that returns the top searches in a collection including there count

db.search.aggregate([
    {
        $match: {
            keywords: { $not: {$size: 0} }
        }
    },
    { $unwind: "$term" },
    {
        $group: {
            _id: {$toLower: '$term'},
            count: { $sum: 1 }
        }
    },
    {
        $match: {
            count: { $gte: 2 }
        }
    },
    { $sort : { count : -1} },
    { $limit : 100 }
]);

I am trying to move this to a C# function and I am getting the error :

MongoDB.Driver.MongoCommandException: 'Command aggregate failed: A pipeline stage specification object must contain exactly one field..'

Here is my C# version, can anyone see what I am missing?

var pipeline = new BsonDocument[] {
new BsonDocument
{
    {
        "$match",
        new BsonDocument {{"keywords", new BsonDocument {{"$not", new BsonDocument {{"$size", 0}}}}}}
    }
},
new BsonDocument {{"$unwind", "$term"}},
new BsonDocument
{
    {
        "$group", new BsonDocument
        {
            {"_id", new BsonDocument {{"$toLower", "$term"}}},
            {
                "count", new BsonDocument
                {
                    {"$sum", 1}
                }
            }
        }
    }
},
new BsonDocument
{
    {
        "$match", new BsonDocument
        {
            {"count", new BsonDocument {{"$gte", 2}}}
        }
    },
    {
        "$sort", new BsonDocument
        {
            {"count", -1}
        }
    },
    {"$limit", 100}
}
};

var result = collection.Aggregate<BsonDocument>(pipeline).ToListAsync();
Console.WriteLine(result);

Solution

  • $match, $sort and $limit should be separate Aggregation Pipeline stages. In your case they have one root BsonDocument, try:

    ...
    new BsonDocument
    {
        {
            "$match", new BsonDocument
            {
                {"count", new BsonDocument {{"$gte", 2}}}
            }
        }
    },
    new BsonDocument()
    {
        { "$sort", new BsonDocument
            {
                {"count", -1}
            }
        }
    },
    new BsonDocument()
    {
        { "$limit", 100 }
    }