How I can merge sub-document (as array) on mongodb collection -
hello have collection:
{ "_id" : objectid("508d27069cc1ae293b36928d"), "title" : "this title", "body" : "this body text.", "created_date" : isodate("2012-10-28t12:41:39.110z"), "comments" : [ { "subject" : "this coment 1", "body" : "this body of comment 1.", "author_id" : objectid("508d345f9cc1ae293b369296"), "created_date" : isodate("2012-10-28t13:34:23.929z") }, { "subject" : "this coment 2", "body" : "this body of comment 2.", "author_id" : objectid("508d34739cc1ae293b369297"), "created_date" : isodate("2012-10-28t13:34:43.192z") }, { "subject" : "this coment 3", "body" : "this body of comment 3.", "author_id" : objectid("508d34839cc1ae293b369298"), "created_date" : isodate("2012-10-28t13:34:59.336z") } ] }
so, on 1 page @ dashboard want see comments, how can that? how can comments each post in single collection, how can identify each comment (for editing or removing)?
upd1:
this doc posts collection. want this:
[ ..., { "_generated_id_for_identify": [what data?], "subject" : "this coment 1", "body" : "this body of comment 1.", "author_id" : objectid("508d345f9cc1ae293b369296"), "created_date" : isodate("2012-10-28t13:34:23.929z") }, { "_generated_id_for_identify": [what data?], "subject" : "this coment 2", "body" : "this body of comment 2.", "author_id" : objectid("508d34739cc1ae293b369297"), "created_date" : isodate("2012-10-28t13:34:43.192z") }, ..., { "_generated_id_for_identify": [what data?], "subject" : "this coment n", "body" : "this body of comment n.", "author_id" : objectid("508d34839cc1ae293b369298"), "created_date" : isodate("2012-10-28t13:34:59.336z") }, ... ]
with aggregate in posts collection , matching "_id" , using unwind in comments , proyection can obtain new collection of comments in results key.
db.posts.aggregate([ {$match:{_id:objectid("508d27069cc1ae293b36928d")}}, {$unwind:"$comments"}, {$project:{ "_id":{id:"$_id",dt:"$comments.created_date"}, subject:"$comments.subject", body:"$comments.body", "autor_id":"$comments.author_id", "created_date":"$comments.created_date"}} ]).result
but simple query matching posts._id obtain post.comments
Comments
Post a Comment