Search on multiple collections in MongoDB

前端 未结 7 1979
自闭症患者
自闭症患者 2020-12-01 01:28

I know the theory of MongoDB and the fact that is doesn\'t support joins, and that I should use embeded documents or denormalize as much as possible, but here goes:

7条回答
  •  甜味超标
    2020-12-01 01:54

    You can achieve this using $mergeObjects by MongoDB Driver Example Create a collection orders with the following documents:

    db.orders.insert([
      { "_id" : 1, "item" : "abc", "price" : 12, "ordered" : 2 },
      { "_id" : 2, "item" : "jkl", "price" : 20, "ordered" : 1 }
    ])
    

    Create another collection items with the following documents:

    db.items.insert([
      { "_id" : 1, "item" : "abc", description: "product 1", "instock" : 120 },
      { "_id" : 2, "item" : "def", description: "product 2", "instock" : 80 },
      { "_id" : 3, "item" : "jkl", description: "product 3", "instock" : 60 }
    ])
    

    The following operation first uses the $lookup stage to join the two collections by the item fields and then uses $mergeObjects in the $replaceRoot to merge the joined documents from items and orders:

    db.orders.aggregate([
       {
          $lookup: {
             from: "items",
             localField: "item",    // field in the orders collection
             foreignField: "item",  // field in the items collection
             as: "fromItems"
          }
       },
       {
          $replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$fromItems", 0 ] }, "$$ROOT" ] } }
       },
       { $project: { fromItems: 0 } }
    ])
    

    The operation returns the following documents:

    { "_id" : 1, "item" : "abc", "description" : "product 1", "instock" : 120, "price" : 12, "ordered" : 2 }
    { "_id" : 2, "item" : "jkl", "description" : "product 3", "instock" : 60, "price" : 20, "ordered" : 1 }
    

    This Technique merge Object and return the result

提交回复
热议问题