简体   繁体   中英

How to query multiple collections of MongoDB?

I have a Parts collection

{
  "_id": {
    "$oid": "5c735f7fbc162b1ee5cdacca"
  },
  "@pno": "10701",
  "pname": "When Harry Met Sally",
  "qoh": "120",
  "price": "19.99",
  "level": "30"
}

and an Orders collection

{
  "_id": {
    "$oid": "5c735fcebc162b1ee5cdaf1a"
  },
  "@ono": "1022",
  "@takenBy": "1001",
  "@customer": "2222",
  "receivedDate": "1995-02-13",
  "shippedDate": "1995-02-20",
  "items": {
    "item": [
      {
        "partNumber": "10601",
        "quantity": "1"
      },
      {
        "partNumber": "10701",
        "quantity": "1"
      }
    ]
  }
}

So the question is how to display the names of parts(pname) ordered by each customer by querying those two collections(how to match @pno in Parts with partNumber in Orders)? Thanks!

              {$unwind:{
                        path:"$items.item",
                        preserveNullAndEmptyArrays:true
             }},

         {
           $lookup: {
            from: "Parts",
            localField: "items.partNumber",
            foreignField: "pno",
            as: "partsDetails"
          }
        },

After you can group this.

You should use lookup aggregation operator. https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

db.getCollection('Parts').aggregate([
    {$unwind:"$items.item"},
    {
      $replaceRoot: { newRoot: { $mergeObjects: [ "$$ROOT","$items.item" ] } }
    },      
    {$lookup:
        {
            from: "Details",
            localField: "partNumber",
            foreignField: "@pno",
            as: "partTitle"
        }
    },
    { $project: { items: 0 } },
    {
      $replaceRoot: { 
        newRoot: { $mergeObjects: [ "$$ROOT",{$arrayElemAt:["$partTitle",0]} ] } 
    }
    },     
    { $project: { partTitle: 0 } },
]);

Result:

{
    "_id" : ObjectId("5c735f7fbc162b1ee5cdacca"),
    "@ono" : "1022",
    "@takenBy" : "1001",
    "@customer" : "2222",
    "receivedDate" : "1995-02-13",
    "shippedDate" : "1995-02-20",
    "partNumber" : "10701",
    "quantity" : "1",
    "@pno" : "10701",
    "pname" : "When Harry Met Sally",
    "qoh" : "120",
    "price" : "19.99",
    "level" : "30"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM