简体   繁体   中英

How to query the whole collections including reference collections in MongoDB?

I am using MongoDB. I have three collections. Posts, types and categories. Posts have reference ids for types and categories like the following;

Post Collection : {"name":"Post One", types:["typeoneId","typetwoId","typethreeId"], categories:["catOneId", "catTwoId", "catThreeId"]});

Type Collection : {"name": "Type One", "_id":"typeoneId"}, ...

Category Collection : {"name": "category one", "_id":"catOneId"}, ....

I want to query as one big collection including all informations about post, type and category. How can I query in Mongodb?

You can't do this with MongoDB alone. What you will have to do is run subsequent queries for type _ids in the types array to populate those (as well as categories). This is one query for each POST and then two subsequent queries per post. There may be faster ways to do this as well.

For Mongoose, you can use populate

Post.find().populate('types').populate('categories')

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