I have two collections like checklists and tasks. Two schemas will look like below
checklist schema will look like beow
{
"_id": "5b7d0f77e231b6b530b0ee5a",
"audit_checklist_type": "Weekly"
}, {
"_id": "5b7d3f33e7a57f38084efb09",
"audit_checklist_type": "Daily"
}
Tasks Schema will look like below
{
"_id": "5b7d65daf74be318e8378cf9",
"checklist_id": "5b7d3f33e7a57f38084efb09"
}, {
"_id": "5b7d662df74be318e8378cfb",
"checklist_id": "5b7d3f33e7a57f38084efb09"
}
my query is
AuditChecklist.aggregate([
{
$match: {
$and: [
audit_checklist_type: "Daily"
]
},
},
{
$lookup: {
from: 'AuditTask',
localField: '_id',
foreignField: 'checklist_id',
as: 'TaskData',
},
},
]).exec()
I'm trying to get the output like
{
"_id": "5b7d3f33e7a57f38084efb09",
"TaskData ": [{
"_id": "5b7d65daf74be318e8378cf9",
"checklist_id": "5b7d3f33e7a57f38084efb09"
},
{
"_id": "5b7d662df74be318e8378cfb",
"checklist_id": "5b7d3f33e7a57f38084efb09"
}
]
}
But for me resulting TaskData output is empty. Any help is greatly appreciated. Thanks in advance!
The $lookup operator is an aggregation operator or an aggregation stage, which is used to join a document from one collection to a document of another collection of the same database based on some queries. Both the collections should belong to the same databases.
For performing MongoDB Join two collections, you must use the $lookup operator. It is defined as a stage that executes a left outer join with another collection and aids in filtering data from joined documents. For example, if a user requires all grades from all students, then the below query can be written: Students.
Mongoose's populate() method does not use MongoDB's $lookup behind the scenes. It simply makes another query to the database. Mongoose does not have functionalities that MongoDB does not have. populate() just makes two or more queries.
Mongoose middleware also supports pre('aggregate') and post('aggregate') hooks. You can use aggregation middleware to transform the aggregation pipeline.
Mongooose pluralise the database name So instead of using AuditTask
you should use audittasks
OR
You can first import the database in your file like
import AuditTask from './AuditTask`
or
const AuditTask = require('./AuditTask')
and use it in your $lookup
aggregation
{ '$lookup': {
'from': AuditTask.collection.name,
'localField': '_id',
'foreignField': 'checklist_id',
'as': 'TaskData'
}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With