简体   繁体   中英

mongodb: how to get documents from more than 2 collections

i've got 2 collections in mongodb

 collection1 **user's**

_id:ObjectId("5a1bedd219001b168e33835e")
password:$2a$05$H5wz7kCm/UIGYpvGWruV0eRd.Blgndd4i8pzZcyW7uCG3U4kUzZM2
socket_id:ljlZzY73BZjnwjZBAAAD
nickName:des
email:desmond.dd31@gmail.com
__v:0

collection2 **messages**

_id:ObjectId("5a1bedd219001b168e33835e")
userId:5a1bedd219001b168e33835e
message: test
time: 2017-11-28 16:57:44.000
__v:0

i want to get messages of each user from the "messages collection", the userId in the messages collection is the object id of the user from the users collection.

what is the best way to get documents from more than 2 collections??

You must perform a lookup query and it works only for MongoDB > 3.2+. More info here

use lookup if having 3.4 or greater version on mongodb

  $lookup:
 {
   from: <collection to join>,
   localField: <field from the input documents>,
   foreignField: <field from the documents of the "from" collection>,
   as: <output array field>
 }

for more reference go here $Lookup

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