Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js mongodb中子文档数组中的排除字段_Node.js_Mongodb_Aggregation Framework - Fatal编程技术网

Node.js mongodb中子文档数组中的排除字段

Node.js mongodb中子文档数组中的排除字段,node.js,mongodb,aggregation-framework,Node.js,Mongodb,Aggregation Framework,我有两份文件 图像文档: {_id:123,user:{user_sub_docuemnt},thumb:'dqwdqwdqwdw'} {_id:444, user:{user_sub_document}, attach:[{_id:123, user:{user_sub_docuemnt}, thumb:'dqwdqwdqwdw'} ] } post文档: {_id:123,user:{user_sub_docuemnt},th

我有两份文件

图像
文档:

{_id:123,user:{user_sub_docuemnt},thumb:'dqwdqwdqwdw'}
{_id:444,
 user:{user_sub_document},
 attach:[{_id:123,
          user:{user_sub_docuemnt},
          thumb:'dqwdqwdqwdw'}
        ]
 }
post
文档:

{_id:123,user:{user_sub_docuemnt},thumb:'dqwdqwdqwdw'}
{_id:444,
 user:{user_sub_document},
 attach:[{_id:123,
          user:{user_sub_docuemnt},
          thumb:'dqwdqwdqwdw'}
        ]
 }
user\u sub\u文档
包含
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\u sub\u文档,所以我尝试了这个方法

{$project:{content:1,attach:1,'attach.user':0,pub_date:1,'user.avatar':1}},
这将给我一个错误
顶级id字段是当前唯一支持排除的字段


请帮我做这个

您可以通过一个简单的
find()
语句来实现这一点:

Post.find({"user._id":{$in:idArr}},
          {"content":1,
           "user.avatar":1,
           "pub_date":1,
           "attach.user.avatar":1})
如果您出于某种原因选择聚合,您可以修改
聚合管道
,如下所示:

  • $match
    使用特定用户ID匹配记录
  • $project
    仅显示必填字段
代码:


很好,很有效。但这不会返回没有附加的帖子,我想这是因为
{$unwind:$attach},
,知道如何解决这个问题吗???@paynestrike-我修改了我的解决方案。请查收。不需要使用
$unwind