首页 > 解决方案 > 仅检索 MongoDB 集合中对象数组中的查询元素并将其添加到另一个文档中作为参考

问题描述

假设您在我的收藏中有以下文档:

{  

"_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" }
      }
    }
  )

ObjectId("562e7c594c12942f08fe4192")主要问题是我想添加这个 Asset1 并通过在 test2 集合中引用它来只取红色而不是整个数组。我如何使用猫鼬做到这一点?

这是我引用的 Test2 Schema

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

标签: node.jsmongodbexpressmongoose

解决方案


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

$unwind - 展开 Shapes 数组

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

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

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

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

推荐阅读