我正在将数组转换为 mongo 中的地图。
"items":[
{
"id":"AB-02",
"qty":2
},
{
"id":"AB-03",
"qty":0
},
{
"id":"AB-03",
"qty":9
}
]
成为
"items":{
"AB-02":{
"id":"AB-02",
"qty":2
},
"AB-03":{
"id":"AB-03",
"qty":0
},
"AB-04":{
"id":"AB-03",
"qty":9
}
}
在数组版本中,根据items
中的元素数量进行查询非常容易,但是我如何使用后一种格式的items
来做到这一点? 例如,查询那些items
有 7 个元素的文档?
从 MongoDB 3.4.4 及更高版本开始,您可以使用将数组转换为单个文档的 $arrayToObject
运算符,数组应该是包含两个字段的文档列表, k
和 v
其中:
k
字段包含字段名称。
v
字段包含字段的值。
因此,您需要创建一个管道,该管道items
首先
"items":[
{
"id":"AB-02",
"qty":2
},
{
"id":"AB-03",
"qty":0
},
{
"id":"AB-03",
"qty":9
}
]
自
"items" : [
{
"k" : "AB-02",
"v" : {
"id" : "AB-02",
"qty" : 2.0
}
},
{
"k" : "AB-03",
"v" : {
"id" : "AB-03",
"qty" : 0.0
}
},
{
"k" : "AB-03",
"v" : {
"id" : "AB-03",
"qty" : 9.0
}
}
]
$map
使用表达式正确执行此操作
"$map": {
"input": "$items",
"as": "item",
"in": {
"k": "$$item.id",
"v": "$$item"
}
}
因此,最终管道可以将上述所有运算符包装到一个阶段中,$addFields
为:
db.collection.aggregate([
{
"$addFields": {
"items": {
"$arrayToObject": {
"$map": {
"input": "$items",
"as": "item",
"in": {
"k": "$$item.id",
"v": "$$item"
}
}
}
}
}
}
])