node.js - 仅检索 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"
},
});
解决方案
使用下面的查询,它使用$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"
}
]);
推荐阅读
- regex - 正则表达式检查包含“E”指数的 DEFINE 数字集
- google-analytics - 链接点击数和推荐数之间的差异
- powershell - 从 Power shell 窗口捕获非 Power shell 内部命令的可见文本
- python - Python - 获取当前风扇速度和每个 CPU 功耗
- android - 如何在kotlin android的MaterialButton中获取背景颜色
- linux - 通过 jenkins 将参数传递给远程机器中的 shell 脚本
- android - AppAuth-Android 在处理非分层 URI 回调意图时出现奇怪问题
- php - 无法使用谷歌日历 api php 创建活动
- limesurvey - 是否可以将 Limesurvey 从 v 1.9 升级到 4.2
- java - okhttp3 MediaType.parse 致命异常:java.lang.IncompatibleClassChangeError