MongoDB:项目到具有最小字段值的数组项

时间:2017-04-12 08:49:02

标签: mongodb mongodb-query aggregation-framework mongodb-.net-driver

假设我的集合包含如下所示的项目:

{
    "items" : [
        {
            "item_id": 1,
            "item_field": 10
        },
        {
            "item_id": 2,
            "item_field": 15
        },
        {
            "item_id": 3,
            "item_field": 3
        },
    ]
}

我可以以某种方式选择items的条目item_field的最低值,在这种情况下是item_id 3的那个吗?

我可以使用聚合框架。如果你能给我C#驱动程序的代码,那就是奖励点。

3 个答案:

答案 0 :(得分:1)

您可以使用$unwind分隔项目条目。 然后{_ 3}}按item_field asc然后$sort

db.coll.find().pretty()
{
    "_id" : ObjectId("58edec875748bae2cc391722"),
    "items" : [
        {
            "item_id" : 1,
            "item_field" : 10
        },
        {
            "item_id" : 2,
            "item_field" : 15
        },
        {
            "item_id" : 3,
            "item_field" : 3
        }
    ]
}

db.coll.aggregate([
  {$unwind: {path: '$items', includeArrayIndex: 'index'}}, 
  {$sort: { 'items.item_field': 1}},
  {$group: {_id: '$_id', item: {$first: '$items'}}} 
])
{ "_id" : ObjectId("58edec875748bae2cc391722"), "item" : { "item_id" : 3, "item_field" : 3 } }

答案 1 :(得分:1)

我们可以使用以下查询获得预期结果

10.2

结果是

db.testing.aggregate([{$unwind:"$items"}, {$sort: { 'items.item_field': 1}},{$group: {_id: "$_id", minItem: {$first: '$items'}}}])

答案 2 :(得分:1)

您可以通过以下方式使用$reduce表达式。

以下查询会将initialValue设置为$items.item_field的第一个元素,然后在$lt上进行item_field比较,如果为true,则设置为$$this $$value,如果为false则保留前一个值,$reduce所有值都可以找到最小元素,$project可以输出最小值。

db.collection.aggregate([
    {
         $project:  {
            items: {
                $reduce: {
                    input: "$items",
                    initialValue:{ 
                         item_field:{ 
                            $let: { 
                                vars: { obj: { $arrayElemAt: ["$items", 0] } },
                                in: "$$obj.item_field"
                            }
                        }
                    },
                    in: {
                          $cond: [{ $lt: ["$$this.item_field", "$$value.item_field"] }, "$$this", "$$value" ] 
                    }
                }
            }
        }
    }
])