MongoDB聚合函数到C#

问题描述 投票:0回答:1

这整个晚上一直困扰着我。

我具有以下MongoDb函数,该函数返回包含计数在内的集合中的顶部搜索

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 }
]);

我正在尝试将其移至C#函数,但出现错误:

MongoDB.Driver.MongoCommandException:'命令聚合失败:A管道阶段规范对象必须只包含一个字段。

这是我的C#版本,任何人都可以看到我所缺少的内容吗?

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

这整夜困扰着我。我有以下MongoDb函数,该函数返回集合中的顶部搜索,其中包括db.search.aggregate([{$ match:{...

c# mongodb mongodb-.net-driver
1个回答
0
投票

$match$sort$limit应该是单独的聚合管道阶段。在您的情况下,它们具有一个根BsonDocument,请尝试:

© www.soinside.com 2019 - 2024. All rights reserved.