在$ group阶段之后如何不指定返回所有字段

时间:2019-07-06 16:26:24

标签: mongodb mongodb-query aggregation-framework

如何对文档中的子数组进行排序并保留父字段? 我有一个这样的收藏:

{ 
    "_id" : ObjectId("5d1757929831633ff8abb638"), 
    "name" : "Carraro Exlusive", 
    "description" : "Carraro Exlusive description", 
    "image" : "image-15", 
    "__v" : 0, 
    "sellers" : [
        {
            "_id" : ObjectId("5d1757929831633ff8abb639"), 
            "product" : ObjectId("5d1757929831633ff8abb638"), 
            "seller" : ObjectId("5d1518582f9254189ca92e59"), 
            "price" : 13, 
            "stock" : 5, 
            "__v" : 0
        }, 
        {
            "_id" : ObjectId("5d175b60cf85a22f745235ee"), 
            "product" : ObjectId("5d1757929831633ff8abb638"), 
            "seller" : ObjectId("5d164802c4dc7811b0f34b86"), 
            "price" : 10, 
            "stock" : 222, 
            "__v" : 0
        }
    ]
}

我想按价格从最小到最大的顺序对内部卖家数组进行排序。

我想要的结果是:

{ 
    "_id" : ObjectId("5d1757929831633ff8abb638"), 
    "name" : "Carraro Exlusive", 
    "description" : "Carraro Exlusive", 
    "category" : ObjectId("5d151ad1b72c830f14374bb4"), 
    "brand" : ObjectId("5d151981b72c830f14374bb2"), 
    "image" : "image-15", 
    "__v" : 0, 
    "sellers" : [
     {
            "_id" : ObjectId("5d175b60cf85a22f745235ee"), 
            "product" : ObjectId("5d1757929831633ff8abb638"), 
            "seller" : ObjectId("5d164802c4dc7811b0f34b86"), 
            "price" : 10, 
            "stock" : 222, 
            "__v" : 0
        },
        {
            "_id" : ObjectId("5d1757929831633ff8abb639"), 
            "product" : ObjectId("5d1757929831633ff8abb638"), 
            "seller" : ObjectId("5d1518582f9254189ca92e59"), 
            "price" : 13, 
            "stock" : 5, 
            "__v" : 0
        }
    ]
}

我看到了以下帖子,但我想保留父字段: Mongodb sort inner array

1 个答案:

答案 0 :(得分:2)

您可以使用以下汇总

db.collection.aggregate([
  { "$unwind": "$sellers" },
  { "$sort": { "sellers.price": 1 }},
  { "$group": {
    "_id": "$_id",
    "sellers": { "$push": "$sellers" },
    "allFields": { "$first": "$$ROOT" }
  }},
  { "$replaceRoot": {
    "newRoot": {
      "$mergeObjects": [
        "$allFields",
        { "sellers": "$sellers" }
      ]
    }
  }}
])