问题描述
我正在尝试使用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
}
]
}
我希望邮递员通过添加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..
有人知道吗?谢谢^^
Anyone knows ?Thanks ^^
推荐答案
您可以使用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
这篇关于猫鼬:查找和过滤嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!