有没有一种简单的方法可以“$push”文档的所有字段? 例如:
假设我有一本 Mongo 藏书:
{author: "tolstoy", title:"war & peace", price:100, pages:800}
{author: "tolstoy", title:"Ivan Ilyich", price:50, pages:100}
我想按作者对它们进行分组 - 对于每个作者,列出他的整个书籍对象:
{ author: "tolstoy",
books: [
{author: "tolstoy", title:"war & peace", price:100, pages:800}
{author: "tolstoy", title:"Ivan Ilyich", price:50, pages:100}
]
}
我可以通过显式推送所有字段来实现这一点:
{$group: {
_id: "$author",
books:{$push: {author:"$author", title:"$title", price:"$price", pages:"$pages"}},
}}
但是有没有捷径,比如:
// Fictional syntax...
{$group: {
_id: "$author",
books:{$push: "$.*"},
}}
最佳答案
你可以使用 $$ROOT
{ $group : {
_id : "$author",
books: { $push : "$$ROOT" }
}}
在这里找到:how to use mongodb aggregate and retrieve entire documents
关于mongodb - Mongo 组并推送 : pushing all fields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22150205/