Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$lookup using mongoose

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!

like image 874
Sasi Rekha Avatar asked Aug 24 '18 07:08

Sasi Rekha


People also ask

What is $lookup in MongoDB?

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.

Can we join 2 collections in MongoDB?

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.

Does Mongoose populate use lookup?

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.

Can I use aggregate in mongoose?

Mongoose middleware also supports pre('aggregate') and post('aggregate') hooks. You can use aggregation middleware to transform the aggregation pipeline.


1 Answers

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'
}}
like image 137
Ashh Avatar answered Sep 30 '22 04:09

Ashh