mongodb - 如何在 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]
]
}
是否可以通过聚合来做到这一点?谢谢你。
解决方案
您可以使用$concatArrays
合并两个字段,然后$group
使其成为二维数组
db.collection.aggregate([
{ "$group": {
"_id": null,
"devices": { "$push": { "$concatArrays": [["$id"], "$locations"] } }
}}
])
[
{
"devices": [
["fff", 5, 5],
["aaa", 7, 7],
["ccc", 9, 9]
]
}
]
推荐阅读
- bixby - 当话语显示为未学习时,如何在新 UI 中强制学习?
- java - 为什么找不到 springBoot {}?
- powershell - 为什么列被跳过?
- android - 我们如何使用批处理脚本将所有应用程序从 android(adb) 复制到 PC?
- javascript - 如何将内部函数值作为参数传递给其回调
- c++ - 如何在 C++ 中编写一个递归函数模板来检查作为参数提供的两个堆栈是否相同?
- php - 带有标准 xml 信封和 pdf 附件的肥皂服务的 CURL 请求
- python - Django TypeError 元组对象不可调用?
- flask - 提交按钮在烧瓶表单上不起作用
- angular - 在 GitHub 页面上部署 Angular 项目