英文:
How to Merge Array and Document Field in Mongo DB
问题
我有这个文档在MongoDB中
[
{
"locations": [5, 5],
"id": "fff"
},
{
"locations": [7, 7],
"id": "aaa"
},
{
"locations": [9, 9],
"id": "ccc"
}
]
而我想要将数组字段和字符串字段合并成一个字段,其中包含它们的组合,就像这样
{
"device": [
["fff", 5, 5],
["aaa", 7, 7],
["ccc", 9, 9]
]
}
是否可以使用聚合来实现这个目标?谢谢。
英文:
I have this document in MongoDB
[
{
"locations": [5, 5],
"id": "fff"
},
{
"locations": [7, 7],
"id": "aaa"
},
{
"locations": [9, 9],
"id": "ccc"
}
]
And I want to merge the array field and string field into a field that contains a combination of them like this
{
"device": [
["fff", 5, 5],
["aaa", 7, 7],
["ccc", 9, 9]
]
}
Is it possible to do this with aggregation? Thank you.
答案1
得分: 1
你可以使用$concatArrays
来合并两个字段,然后使用$group
将其转换为二维数组。
db.collection.aggregate([
{ "$group": {
"_id": null,
"devices": { "$push": { "$concatArrays": ["$id", "$locations"] } }
}}
])
[
{
"devices": [
["fff", 5, 5],
["aaa", 7, 7],
["ccc", 9, 9]
]
}
]
英文:
You can use $concatArrays
to merge two fields and then $group
to make it two dimensional array
db.collection.aggregate([
{ "$group": {
"_id": null,
"devices": { "$push": { "$concatArrays": [["$id"], "$locations"] } }
}}
])
[
{
"devices": [
["fff", 5, 5],
["aaa", 7, 7],
["ccc", 9, 9]
]
}
]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论