c# - MongoDB 聚合函数到 C#

标签 c# mongodb mongodb-.net-driver

这件事困扰了我一整夜。

我有以下 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: 'Command aggregate failed: A pipeline stage specification object must contain exactly one field..'

这是我的 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);

最佳答案

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

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

关于c# - MongoDB 聚合函数到 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61432899/

相关文章:

c# - 返回结束晚于 10 天的拍卖

javascript - 选择子文档所在位置

mongodb - 如何在 Ubuntu 18.04 仿生上安装 Mongodb 3.4

c# - 使用 ContinueOnError 批量插入

c# - 重新加载场景时,如何使我的 Singleton MonoBehaviour 类实例以新实例开始?

c# - 后台 worker 无法处理异常

mongodb - 使用 MongoCollection.FindAll 两次返回相同的文档

c# - MongoDB 引用的最佳实践

c# - StructureMap - 扫描 - 具有基本实现和特定功能的通用接口(interface)

c++ - 构建 mongo c++ 驱动程序