Mongoose:查找和过滤嵌套数组 [英] Mongoose :Find and filter nested array
问题描述
我正在尝试使用 Find()
命令查找整个文档并使用条件过滤嵌套数组.
I'm trying to find a whole document with Find()
command and filter a nested array with a condition.
这里有一块使用过的架构:
Here a piece of the used Schema :
var ListSH = new Schema({
name: { type: String, unique: true, required: true},
subject : String,
recipients : [
Schema({
uid : { type : ObjectId, required : true, ref:'User', unique: true},
status : { type : Number, default : 1 }
},{_id: false})
]
};
目前我做 ListModel.findOne({ _id : req.params.id_list, function(err,list){...};
邮递员告诉我:
{
"_id": "57e6bcab6b383120f0395aed",
"name": "Emailing listname",
"subject": "List subject",
"recipients": [
{
"uid": "57e932bcbbf0e9e543def600",
"status": 0
},
{
"uid": "57e93266c3c0b1dc1625986f",
"status": 1
}
]
}
我希望 Postman 通过添加一个 recipients.status : 1
条件来返回给我类似的东西
I'd like Postman to return me something like that by adding a recipients.status : 1
condition
{
"_id": "57e6bcab6b383120f0395aed",
"name": "Emailing listname",
"subject": "List subject",
"recipients": [
{
"uid": "57e93266c3c0b1dc1625986f",
"status": 1
}
]
}
我已经试过了 ListModel.findOne({ _id : req.params.id_list, 'recipients.status' : 1}, function(err,list){...};
还有一些奇怪的东西,比如 populate([$match('recipients.status : 1)]);
但没有成功..
and something weird like populate([$match('recipients.status : 1)]);
but with no success..
有人知道吗?谢谢^^
推荐答案
您可以使用 aggregate
像这样简单地获得它
You can use aggregate
to get it in an easy way like this
ListModel.aggregate(
{ $match: {_id: ObjectId("57e6bcab6b383120f0395aed")}},
{ $unwind: '$recipients'},
{ $match: {'recipients.status':1}})
输出
{
"_id" : ObjectId("57e6bcab6b383120f0395aed"),
"name" : "Emailing listname",
"subject" : "List subject",
"recipients" : {
"uid" : "57e93266c3c0b1dc1625986f",
"status" : 1
}
}
要详细了解聚合,请参阅文档此处
To understand aggregation in details see the docs here
这篇关于Mongoose:查找和过滤嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!