Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

183
Views
How to get data from multiple collections in mongodb using mongoose?

I have 3 collections in mongoDB with the following structure

Users:

"name":""
"email":""
"phone":""
"city":""
"customerID":""

Ships:

"address":""
"city":""
"pincode":""
"porderID":""
"customerID":""

Orders:

"productName":""
"quantity":""
"pricing":""
"mrp":""
"porderID":""
"customerID":""

How do I write a get request or an aggregate function that returns all customerIDs in a json like this?

[{

customerID:"",
BuyOrder:[{
porderID:"",
productName:"",
quantity:""
ShipmentDetail:[
address:""
city:""
pincode:""
]
}],

customerID:"",
BuyOrder:[{
porderID:"",
productName:"",
quantity:""
ShipmentDetail:[
address:""
city:""
pincode:""
]
}],

}]

Any suggestions would be helpful.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Is not quite clear what do you want... without an input/output example, without a valid JSON... is not easy but I think you are looking for something like this:

This query is a nested $lookup where for each user join the collection with orders using the customerID, and also, orders is joined with ships using customerID too.

db.users.aggregate([
  {
    "$lookup": {
      "from": "orders",
      "localField": "customerID",
      "foreignField": "customerID",
      "as": "BuyOrder",
      "pipeline": [
        {
          "$lookup": {
            "from": "ships",
            "localField": "customerID",
            "foreignField": "customerID",
            "as": "ShipmentDetail"
          }
        }
      ]
    }
  },
  
])

Example here

You also can add a $project stage to output only fields you want, like this example where the result is:

[
  {
    "BuyOrder": [
      {
        "ShipmentDetail": [
          {
            "address": "",
            "city": "",
            "pincode": ""
          }
        ],
        "porderID": "",
        "pricing": "",
        "productName": "",
        "quantity": ""
      }
    ],
    "customerID": ""
  }
]
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!