问题描述
我的文件类似 {'a':1,'z':{'b':2,'c':3,}}
。
我想 {'a':1,'b':2,'c':3}
。
我可以用
aggregate({'$project': {'b': '$z.b', 'c': '$z.c'}})
是否可以在不手动列出子文档中的所有键的情况下执行此操作?
Is it possible to do it without listing all of the keys in the subdocument manually?
推荐答案
使用MongoDB 3.4,您可以使用 $ objectToArray
和 $ arrayToObject
带 $ replaceRoot
为了改变这个:
With MongoDB 3.4 you can use $objectToArray
and $arrayToObject
with $replaceRoot
in order to change this:
db.wish.aggregate([
{ "$replaceRoot": {
"newRoot": {
"$arrayToObject": {
"$concatArrays": [
[{ "k": "a", "v": "$a" }],
{ "$objectToArray": "$z" }
]
}
}
}}
])
甚至这个长咒语甚至没有指定a
属性:
Or even this long incantation without even specifying the "a"
property:
db.wish.aggregate([
{ "$replaceRoot": {
"newRoot": {
"$arrayToObject": {
"$reduce": {
"input": {
"$filter": {
"input": { "$objectToArray": "$$ROOT" },
"as": "r",
"cond": { "$ne": [ "$$r.k", "_id" ] }
}
},
"initialValue": [],
"in": {
"$concatArrays": [
"$$value",
{ "$cond": {
"if": { "$gt": [ "$$this.v", {} ] },
"then": { "$objectToArray": "$$this.v" },
"else": ["$$this"]
}}
]
}
}
}
}
}}
])
两者都产生:
{ "a" : 1, "b" : 2, "c" : 3 }
在将来的版本中不需要使用 $ concatArrays
,因为会有 $ mergeObjects
运算符会使它更清洁。
The funny use of $concatArrays
should not be necessary in future versions since there will be a $mergeObjects
operator which will make that a bit cleaner.
但你基本上可以在客户端代码中做同样的事情。例如,在shell的JavaScript中:
But you can basically just do the same thing in client code pretty simply. For example in JavaScript for the shell:
db.wish.find().map( doc => (
Object.assign({ a: doc.a }, doc.z )
))
或者再次没有a
的版本:
db.wish.find().map( doc =>
Object.keys(doc).filter(k => k !== '_id').map(k =>
( typeof(doc[k]) === "object" ) ?
Object.keys(doc[k]).map(i => ({ [i]: doc[k][i] }))
.reduce((acc, curr) => Object.assign(acc,curr),{})
: { [k]: doc[k] }
).reduce((acc,curr) => Object.assign(acc,curr),{})
)
产生相同的输出
{ "a" : 1, "b" : 2, "c" : 3 }
这篇关于在没有列出所有键的情况下将子字段提升到顶级投影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!