![](/img/trans.png)
[英]Merge and aggregate some fields of two or more collections with identical schema mongodb
[英]How to merge two collections in mongodb, aggregate mongodb
我有 2 个 collections:配置和点 点集合有一个名称字段,用于存储配置集合的 id
假设集合有一个数组,其中包含要搜索的对象,如何组合两个排序规则。
配置:
{
"find": true,
"points": [{
"image": true,
"brand": true,
"_id": {
"$oid": "61f0ad909535d94c98056e11"
},
"name": "ABC"
}, {
"image": true,
"brand": true,
"_id": {
"$oid": "61f0ade99535d94c98056e17"
},
"name": "Odido"
}]
}
积分
{
"name": "61f0ad909535d94c98056e11",
"userID": "61c49f94a02ff82b484cc6d0",
enter code here
"create_date": {
"$date": "2022-01-27T02:53:52.473Z"
}
}
我想得到这个结果,好吧,或者类似的东西
{
"name": "61f0ad909535d94c98056e11",
"userID": "61c49f94a02ff82b484cc6d0",
"config_name": {
"image": true,
"brand": true,
"_id": {
"$oid": "61f0ad909535d94c98056e11"
},
"name": "ABC"
},
"create_date": {
"$date": "2022-01-27T02:53:52.473Z"
}
}
我正在尝试使用这样的查询
Points.aggregate([
{
$lookup: {
from: "configs",
localField: "name",
foreignField: "_id",
as: "configs",
},
},
]);
在此先感谢您的帮助:)
db.points.aggregate([
{
$match: { "name": "61f0ad909535d94c98056e11" }
},
{
$set: { "name": { "$toObjectId": "$name" } }
},
{
$lookup: {
from: "configs",
localField: "name",
foreignField: "points._id",
as: "config_name"
}
},
{
$set: {
"config_name": {
"$first": {
"$filter": {
"input": { "$first": "$config_name.points" },
"as": "item",
"cond": { "$eq": [ "$name", "$$item._id" ] }
}
}
}
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.