【问题标题】:finding document in mongodb with specific id and username在 mongodb 中查找具有特定 ID 和用户名的文档
【发布时间】:2014-05-16 00:47:43
【问题描述】:
{
    "data": [
        {
          "_id": 555,
          "username": "jackson",
          "status": "i am coding",
          "comments": [
            {
              "user": "bob",
              "comment": "bob me "
            },
            {
              "user": "daniel",
              "comment": "bob the builder"
            },
            {
              "user": "jesus",
              "comment": "bob the builder"
            },
            {
              "user": "hunter",
              "comment": "bob the builder"
            },
            {
              "user": "jeo",
              "comment": "bob the builder"
            },
            {
              "user": "jill",
              "comment": "bob the builder"
            }
          ]
        }
    ]
}

所以我想用_id :555user:bob 得到结果,我尝试了下面的代码,但我不能让它工作它返回空数组

app.get('/all',function(req , res){
  db.facebook.find({_id:555},{comments:[{user:"bob"}]},function(err,docs){res.send(docs,{data:docs});});
} );

我希望结果如下所示,并带有user:bob 的评论

{
    "_id": 555,
    "username": "jackson",
    "status": "i am coding",
    "comments": [
        {
        "user": "bob",
        "comment": "bob me "
        }
    ]
}

【问题讨论】:

    标签: json node.js mongodb


    【解决方案1】:

    只有聚合或 mapReduce 可以在输出中从子数组中排除项目。最短的是使用 $redact:

    db.facebook.aggregate({
     $redact:{
          $cond:{ 
             if:{$and:[{$not:"$username"},{$ne:["$user","bob"]}]}, 
             then: "$$PRUNE", 
             else: "$$DESCEND" 
          }
     }
    })
    

    解释: $reduct 将从整个文档开始应用于每个子文档。对于每个子文档,$reduct 要么修剪它,要么下降。我们想保留顶级文档,这就是我们有{$not:"$username"} 条件的原因。它可以防止顶级文档被修剪。在下一级,我们有comments 数组。 $prune 将条件应用于 cmets 数组的每个项目。第一个条件 {$not:"$username"} 对所有 cmets 为真,第二个条件 {$ne:["$user","bob"]} 对于 user!="bob" 的所有子文档都为真,因此此类文档将被修剪。

    更新:在 node.js 中使用 mongodb 原生驱动程序

    db.facebook.aggregate([{
     $redact:{
          $cond:{ 
             if:{$and:[{$not:"$username"},{$ne:["$user","bob"]}]}, 
             then: "$$PRUNE", 
             else: "$$DESCEND" 
          }
     }
    }], function(err,docs){})
    

    还有一点:$prune 是新运算符,仅在 MongoDB 2.6 中可用

    【讨论】:

    • 我无法理解这个 $redact 你能用普通功能解释一下吗
    • 那么我在哪里可以添加我的错误函数和结果?即 function(err,docs) {res.send{data:docs} } .
    猜你喜欢
    • 2015-02-13
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 2016-03-21
    • 2016-06-18
    • 2015-09-02
    • 1970-01-01
    相关资源
    最近更新 更多