首页 > 解决方案 > MongoDb RunCommand 查询嵌入式数组

问题描述

我需要使用“db.RunCommand”从嵌入到集合中的数组中获取项目。我刚开始使用 MongoDB,我很难查看 MongoDB 文档,因为我找不到很多直接使用“RunCommand”方法的示例。

所以如果我有这个例子

[
   {
     "Brand": {
         "Name": "Brand name 1",
         "Products": [
            {
                 "Product":  "Product 1",
                 "Price": 20.33
            },
             // i need to get only the following object
            { 
                 "Product":  "Product 2",
                 "Price": 10.33
            },
            {
                 "Product":  "Product 2",
                 "Price": 15.33
            }
         ]
      }
   }
]

那么如何将查询构造到“RunCommand(--query here--)”中以仅获取“Product 2”?所以结果是

{ 
   "Product":  "Product 2",
   "Price": 10.33
}

如果需要,我使用 C# .net Core 和 MongoDB 驱动程序

标签: c#mongodb

解决方案


db.runCommand({
    aggregate: "your_collection",
    "pipeline": [
        {$match: {"_id": ObjectId("5fcd2d3b08c6590a0cd04630")}},
        {$project: {
            _id: 0, "products": {"$arrayElemAt": ["$a.Brand.Products", 0]}}}, 
        {$project: {"products": {"$arrayElemAt": ["$products", 1]}}}],
    cursor: {}})

推荐阅读