How to return all fields without specify after $group stage

橙三吉。 提交于 2021-01-27 10:47:35

问题


How to sort the child array in a document and keep the parent fields? I have a collection like this:

{ 
    "_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
        }
    ]
}

and I want to sort the inner sellers array by price from smallest to largest.

The result I want is:

{ 
    "_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
        }
    ]
}

I saw the following post, but I want to keep the parent fields: Mongodb sort inner array


回答1:


You can use below aggregation

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


来源:https://stackoverflow.com/questions/56915860/how-to-return-all-fields-without-specify-after-group-stage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!