仅检索MongoDB集合中对象数组中的查询元素,并将其添加到另一个文档中作为参考

时间:2019-06-14 08:04:18

标签: node.js mongodb express mongoose

假设您的收藏夹中包含以下文档:

{  

"_id":ObjectId("562e7c594c12942f08fe4192"),
"name": "Asset1"
   "shapes":[  
      {  
     "_id": "5cf10fea4cb6352abcfe094b",
         "shape":"square",
         "color":"blue"
      },
      {  
     "_id": "5cf10fea4cb6352abcfe094c",
         "shape":"circle",
         "color":"red"
      }
   ]
},

{  
   "_id":ObjectId("562e7c594c12942f08fe4193"),
   "name": "Asset2"
   "shapes":[  
      {  
     "_id": "5c7524f76792cf28f80793e3"
         "shape":"square",
         "color":"black"
      },
      {  
     "_id": "5c7524f76792cf28f80793e4"
         "shape":"circle",
         "color":"green"
      }
   ]
}
}

找到这样的特定颜色我也没有问题,

  Test.find(
    {"shapes.color": "red"}, 

    //Match the exact color
    {
      products: {
        $elemMatch: { color: "red" }
      }
    }
  )

主要问题是我想添加此Asset1并通过在test2集合中引用ObjectId("562e7c594c12942f08fe4192")来仅获取红色而不是整个数组。我该如何使用猫鼬呢?

这是我引用的Test2架构

const Test2Schema = new Schema({
anothername: String,
test1Shape: {
type: mongoose.Schema.Types.ObjectId,
ref: "Test"
  },
});

1 个答案:

答案 0 :(得分:0)

使用以下查询,它使用$unwind$match$lookup$out

$ unwind-展开Shapes数组

$ match-过滤匹配的颜色red记录

$ lookup-在Test2 Collection中查找匹配的文档

$ out-用合并的文档覆盖Test2集合

db.Test1.aggregate([
  {
    $unwind: "$shapes"
  },
  {
    $match: {
      "shapes.color": "red"
    }
  },
  {
    $lookup: {
      from: "Test2",
      localField: "_id",
      foreignField: "_id",
      as: "mergeResult"
    }
  },
  {
    $out: "Test2"
  }
]);