如何在MongoDB中合并数组和文档字段

huangapple go评论69阅读模式
英文:

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"] } }
  }}
])

Output

[
  {
    "devices": [
      ["fff", 5, 5],
      ["aaa", 7, 7],
      ["ccc", 9, 9]
    ]
  }
]

huangapple
  • 本文由 发表于 2020年1月6日 15:38:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/59608303.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定