排除 mongodb 中子文档数组中的字段
Exclude field in array of subdocument in mongodb
我有两个文件
image
文件:
{_id:123,user:{user_sub_docuemnt},thumb:'dqwdqwdqwdw'}
post
文件:
{_id:444,
user:{user_sub_document},
attach:[{_id:123,
user:{user_sub_docuemnt},
thumb:'dqwdqwdqwdw'}
]
}
user_sub_document
包含 password
字段,因此我需要排除该字段。
这是我目前拥有的:
Post.aggregate([
{$match: {'user._id': {$in:idArr}}},
{$project:{content:1,attach:1,pub_date:1,'user.avatar':1}},
],function(err,posts){
if(err){
throw err
}else{
res.send(posts)
}
})
这只会限制Post级别的用户,附加数组中还有另一个user_sub_document,所以我尝试了这个
{$project:{content:1,attach:1,'attach.user':0,pub_date:1,'user.avatar':1}},
这会给我一个错误The top-level _id field is the only field currently supported for exclusion
请帮我解决这个问题!
您可以使用简单的 find()
语句实现此目的:
Post.find({"user._id":{$in:idArr}},
{"content":1,
"user.avatar":1,
"pub_date":1,
"attach.user.avatar":1})
如果您出于某种原因选择聚合,您可以按如下方式修改您的aggregation pipeline
:
$match
具有特定用户 ID 的记录。
$project
只有必填字段。
代码:
Post.aggregate([
{$match:{"user._id":{$in:idArr}}},
{$project:{"user.avatar":1,
"attach.user.avatar":1,
"pub_date":1,
"content":1}}],function(err,resp){
// handle response
})
我有两个文件
image
文件:
{_id:123,user:{user_sub_docuemnt},thumb:'dqwdqwdqwdw'}
post
文件:
{_id:444,
user:{user_sub_document},
attach:[{_id:123,
user:{user_sub_docuemnt},
thumb:'dqwdqwdqwdw'}
]
}
user_sub_document
包含 password
字段,因此我需要排除该字段。
这是我目前拥有的:
Post.aggregate([
{$match: {'user._id': {$in:idArr}}},
{$project:{content:1,attach:1,pub_date:1,'user.avatar':1}},
],function(err,posts){
if(err){
throw err
}else{
res.send(posts)
}
})
这只会限制Post级别的用户,附加数组中还有另一个user_sub_document,所以我尝试了这个
{$project:{content:1,attach:1,'attach.user':0,pub_date:1,'user.avatar':1}},
这会给我一个错误The top-level _id field is the only field currently supported for exclusion
请帮我解决这个问题!
您可以使用简单的 find()
语句实现此目的:
Post.find({"user._id":{$in:idArr}},
{"content":1,
"user.avatar":1,
"pub_date":1,
"attach.user.avatar":1})
如果您出于某种原因选择聚合,您可以按如下方式修改您的aggregation pipeline
:
$match
具有特定用户 ID 的记录。$project
只有必填字段。
代码:
Post.aggregate([
{$match:{"user._id":{$in:idArr}}},
{$project:{"user.avatar":1,
"attach.user.avatar":1,
"pub_date":1,
"content":1}}],function(err,resp){
// handle response
})