MongoDB query to match documents whose _id is in an array as part of a subdocument?


Let us create a collection with documents −

> db.demo568.insertOne({ _id: 101, details: [ {id : 101 }, { id:103 } ] });
{ "acknowledged" : true, "insertedId" : 101 }

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

> db.demo568.find();

This will produce the following output −

{ "_id" : 101, "details" : [ { "id" : 101 }, { "id" : 103 } ] }
Following is the query to create second collection:
> db.demo569.insertOne({ _id: 101, details: "John" })
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo569.insertOne({ _id: 102, details: "Chris" })
{ "acknowledged" : true, "insertedId" : 102 }
> db.demo569.insertOne({ _id: 103, details: "David" })
{ "acknowledged" : true, "insertedId" : 103 }

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

> db.demo569.find();

This will produce the following output −

{ "_id" : 101, "details" : "John" }
{ "_id" : 102, "details" : "Chris" }
{ "_id" : 103, "details" : "David" }

Following is the query to match documents whose _id is in an array as part of a subdocument −

> db.demo569.find({ '_id': { '$in': db.demo568.distinct('details.id', {'_id': 101}) }})

This will produce the following output −

{ "_id" : 101, "details" : "John" }
{ "_id" : 103, "details" : "David" }

Updated on: 14-May-2020

132 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements