3

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);
1
  • you might be interested in this approach instead of the unreadable/unmaintainable mess up there. Commented Apr 26, 2020 at 3:01

1 Answer 1

3

$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 }
}
Sign up to request clarification or add additional context in comments.

Comments

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.