Jacek Wojcik
Jacek Wojcik

Reputation: 1253

MongoDB: get _id of document having given value and use it in query

I have two collections:

Users:  
{
_id:12345647890,
email:"[email protected]"  
}  

Documents:
{
_id:0987654321,
owner:1234567890,
text:"aaa"}
{
_id:0987654322,
owner:1234567890,
text:"bbb"}  

I want to find all documents belonging to person with [email protected] email.

I know I can first find _id of a person in Users collection using given email and then find all documents from Documents, but probably there is a way to achieve it in one query, something like:

Documents.find({owner is equal _id taken from Users where Users.email is equal [email protected]})  

Thank you :-)

Upvotes: 1

Views: 37

Answers (1)

Steve Land
Steve Land

Reputation: 4862

You can use the $lookup aggregation pipeline to effect a join between your referenced documents, and combine that with a $match pipeline to filter the results.

db.Users.aggregate([
  { $match: { email: { $eq: 'searchterm' }}},
  { $lookup:
        {
          from: "documents",
          localField: "_id",
          foreignField: "owner",
          as: "user_documents"
         }
  }
])

The official documentation around Mongodb aggregations can be a little sparse on examples, but there are plenty of blogs out there with workable code. Another good resource for code snippets and practical examples will be the unit tests for whatever driver you're using (e.g. c#, java etc).

I should also mention two related points:

  • Just running two queries is often a simple and viable alternative, which you shouldnt discount automatically - provided you dont have enormous collections. In many cases the performance difference may be negligible.

  • With whichever approach you choose, make sure you are indexing your foreign key reference!

Upvotes: 2

Related Questions