Perform $lookup to array of object id's in MongoDB?


For this, use $lookup. This performs a left outer join to an unsharded collection in the same database to filter in documents from the “joined” collection for processing.

Let us first create a collection with documents −

> db.demo395.insertOne({Name:"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5e782317aa3ef9ab8ab207")
}
> db.demo395.insertOne({Name:"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5e782317aa3ef9ab8ab208")
}

Display all documents from a collection with the help of find() method −

> db.demo395.find();

This will produce the following output −

{ "_id" : ObjectId("5e5e782317aa3ef9ab8ab207"), "Name" : "Chris" }
{ "_id" : ObjectId("5e5e782317aa3ef9ab8ab208"), "Name" : "David" }

Let us create a second collection with documents −

> db.demo396.insertOne({"details" : [
...    ObjectId("5e5e782317aa3ef9ab8ab207"),
...    ObjectId("5e5e782317aa3ef9ab8ab208")
...    ]
... }
... )
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5e787817aa3ef9ab8ab209")
}

Display all documents from a collection with the help of find() method −

> db.demo396.find();

This will produce the following output −

{ "_id" : ObjectId("5e5e787817aa3ef9ab8ab209"), "details" : [
ObjectId("5e5e782317aa3ef9ab8ab207"), ObjectId("5e5e782317aa3ef9ab8ab208") ] }

Following is the query to perform $lookup to array of object id's −

> db.demo396.aggregate([
...    { "$lookup": {
...       "from": "demo395",
...       "let": { "details": "$details" },
...       "pipeline": [
...          { "$match": { "$expr": { "$in": [ "$_id", "$$details" ] } } }
...       ],
...       "as": "output"
...    }}
... ])

This will produce the following output −

{ "_id" : ObjectId("5e5e787817aa3ef9ab8ab209"), "details" : [ ObjectId("5e5e782317aa3ef9ab8ab207"), ObjectId("5e5e782317aa3ef9ab8ab208") ], "output" : [ { "_id" : ObjectId("5e5e782317aa3ef9ab8ab207"), "Name" : "Chris" }, { "_id" : ObjectId("5e5e782317aa3ef9ab8ab208"), "Name" : "David" } ] }

Updated on: 02-Apr-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements