Last week, I needed to find articles by user in different DB on the same server. The query won’t be used in code, it is just for a quick check. So I decided to make a subquery between DBs.
The structure is like this:
- MongoDB Server
- account DB
- user Collection
- _id
- username
- etc
- content DB
- article Collection
- _id
- user_id: refer to accounts.user._id
- title
- etc
After some googling and trial and error, I came up with this solution:
- Connect to MongoDB server.
- Run the query below:
use account; db.getCollection('user') .find({ user_name: 'hassan' }, { _id: 1 }) .forEach((user) => { db.getSiblingDB('content') // use content DB to query articles owned by a user .article.find({ user_id: user._id }, { _id: 1, title: 1 }) .forEach((article) => { var result = { user_id: user._id, article_id: article._id, title: article.title }; printjson(result); }); });