如何在MongoDB中将子文档展平到根级别? [英] How to flatten a subdocument into root level in MongoDB?
本文介绍了如何在MongoDB中将子文档展平到根级别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,如果我有这样的文档
For example, if I have a document like this
{
a: 1,
subdoc: {
b: 2,
c: 3
}
}
如何将其转换为这样的格式? (不使用project
)
How can I convert it into a format like this? (without using project
)
{
a: 1,
b: 2,
c: 3
}
推荐答案
您可以使用链接
You can use MongoDB projection i.e $project
aggregation framework pipeline operators as well. (recommended way). If you don't want to use project
check this link
db.collection.aggregation([{$ project {..}}]));
db.collection.aggregation([{$project{ . . }}]);
以下是您的案例示例:
db.collectionName.aggregate
([
{ $project: { a: 1, 'b': '$subdoc.b', 'c': '$subdoc.c'} }
]);
为您提供预期的输出,即
Gives you the output as you expected i.e.
{
"a" : 1,
"b" : 2,
"c" : 3
}
这篇关于如何在MongoDB中将子文档展平到根级别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文