查询MongoDB中的所有子文档

时间:2014-11-20 03:58:08

标签: php mongodb

我有这样的文件:

  {
     author: "ABC1",
     text:"this is a Post",
     details: {
        time: "14/05/2015",
        Edit: "none"
     },
     comments: [
         { 
               comment_text: "Hello",
                user: "alan",
                  time:"20/05/2014 20:44" 
           }, 
         { 
                comment_text: "Hi Every One",
                 user: "bob",
                  time:"20/05/2014 20:44"
          },
         { 
                 comment_text: "Good morning , Alan", 
                 user: "Alan",
                 time:"20/05/2014 20:44"
           },
         { 
                    comment_text: "I'm bob",
                    user: "bob", 
                    time:"20/05/2014 20:44"
            },
              ],
     category: "IT"
   }

我想查询所有拥有用户的子文档:“bob” PHP中的示例: db.posts.find(阵列( “comments.user”=> “中鲍勃”);

我知道这个语法对我不起作用。 如果语法为true,则查找操作将显示为:

                { 
                   comment_text: "I'm bob",
                   user: "bob", 
                   time:"20/05/2014 20:44" 
                },
                { 
                  comment_text: "Hi Every One",
                   user: "bob",
                  time:"20/05/2014 20:44" 
                },

如何更改文档架构呢?

1 个答案:

答案 0 :(得分:2)

哟不需要更改文档架构,您可以通过聚合找到Bob的评论:

db.posts.aggregate([{$unwind:"$comments"},{$project:{"comment_text":"$comments.comment_text","user":"$comments.user","time":"$details.time",_id:0}},{$match:{"user":"bob"}}])