如何对文档中的数组元素进行排序(猫鼬)

时间:2018-05-17 14:49:24

标签: mongodb express mongoose aggregation-framework

当我想选择带有id.My样本结构的文档(基于我的模型)时,如何按降序对addressBook.default进行排序:

{  
  "_id" : ObjectId("9afd8416e7913223b09a89333"),
  "email": "abc@gmail.com",
  "fullName": "william",
  "addressBook": [
     {
       "_id": ObjectId("5afd8416e7913223b09a89333"),
       "default ": 1,
       "country": "hong kong"
     },
     {
       "_id": ObjectId("6afd8416e7913223b09a89333"),
       "default ": 0,
       "country": "india"
     },
     {
       "_id": ObjectId("7afd8416e7913223b09a89333"),
       "default ": 1,
       "country": "thailand"
     },
  ]
}

我用findByID()和sort()函数尝试了类似的东西,但我可以得到我想要的结果。

WebsiteUser.findById(req.user.id).sort('-addressBook.default').exec(function(err,result){
});

当我选择文档ID为

的文档时,我想要的结果
 {  
   "_id" : ObjectId("9afd8416e7913223b09a89333"),
   "email": "abc@gmail.com",
   "fullName": "william",
   "addressBook": [
      {
        "_id": ObjectId("5afd8416e7913223b09a89333"),
        "default ": 1,
         "country": "hong kong"
      },
      {
        "_id": ObjectId("7afd8416e7913223b09a89333"),
        "default ": 1,
        "country": "thailand"
      },
      {
        "_id": ObjectId("6afd8416e7913223b09a89333"),
        "default ": 0,
        "country": "india"
      }
    ]
 }

1 个答案:

答案 0 :(得分:1)

您需要先$unwind addressBook,然后在sort

上应用default
db.collection.aggregate([
  {
    "$unwind": "$addressBook"
  },
  {
    "$sort": {
      "addressBook.default": 1
    }
  },
  {
    "$group": {
      "_id": "$_id",
      "addressBook": {
        "$push": "$addressBook"
      }
    }
  }
])