[英]$project inside MongoDB array
I have MongoDB collection items
with following document:我有 MongoDB 收集
items
与以下文件:
{
data: [{"name": "First"}, {"name": "Second"}],
data2: [{"value": 20}, {"value": 30}]
}
Is there any way to project data2.value
into data.value
on same indexes?有没有办法将
data2.value
投影到同一索引上的data.value
中? I would need this result:我需要这个结果:
{
data: [
{"name": "First", value: 20},
{"name": "Second", value: 30}
]
}
It would like something like that:它想要这样的东西:
db.items.aggregate([{"$project": {"data.X.value": "$data2.X.value", "data2": 0}}]) // Where X "iterate" over all indexes (so 0 and 1).
Lengths of arrays data
and data2
are always same, but it doesn't have to be 2. arrays
data
和data2
的长度始终相同,但不必为 2。
You can try,你可以试试,
data
array data
数组的 object 循环遍历 object$$d
$$d
value
of data2
from particular $$d
object index $$d
object 索引中获取data2
的元素value
db.collection.aggregate([
{
$project: {
data: {
$map: {
input: "$data",
as: "d",
in: {
name: "$$d.name",
value: {
$arrayElemAt: [
"$data2.value",
{ $indexOfArray: ["$data", "$$d"] }
]
}
}
}
}
}
}
])
Playground: https://mongoplayground.net/p/wv1vEVsrHeT游乐场: https://mongoplayground.net/p/wv1vEVsrHeT
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.