cagigas
cagigas

Reputation: 49

Mongodb direct access to ObjectId

I have a "company" collection like this:

{
  "_id" : ObjectId("58c52a26de0bdd9311000004"), 
  "name" : "ed", 
  "projects" : [ ], 
  "__v" : 0, 
  "users" : [
    ObjectId("58c52a36de0bdd9311000007"),
    ObjectId("58c52a54de0bdd931100000a")
  ]
}

I want to get some info from the users; do I have to do a query to get the ObjectID and the another query to each of the users?

Or is there any way to get this info directly from the query to company?

Upvotes: 0

Views: 282

Answers (1)

notionquest
notionquest

Reputation: 39186

You can use lookup aggregation to get the data from user collection assuming both the collections are in same database.

Performs a left outer join to an unsharded collection in the same database to filter in documents from the “joined” collection for processing. The $lookup stage does an equality match between a field from the input documents with a field from the documents of the “joined” collection.

Basic syntax:-

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

MongoDB lookup

Upvotes: 1

Related Questions