当我想选择带有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"
}
]
}
答案 0 :(得分:1)
您需要先$unwind
addressBook
,然后在sort
default
db.collection.aggregate([
{
"$unwind": "$addressBook"
},
{
"$sort": {
"addressBook.default": 1
}
},
{
"$group": {
"_id": "$_id",
"addressBook": {
"$push": "$addressBook"
}
}
}
])