简体   繁体   中英

Query All Subdocument in MongoDB

I have document like this:

  {
     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"
   }

i want to Querying all Subdocument which have user:"bob" Example in PHP: db.posts.find(array("comments.user"=>"bob");

I know this Syntax will not work for me. And If the syntax is true, the Find Operations will show as:

                { 
                   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" 
                },

How can I change Document Schema to do that?

不需要更改文档架构,您可以通过汇总找到Bob的注释:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM