Mongo分组和推送:推送所有领域

2024-02-24

有没有一种简单的方法来“$push”文档的所有字段? 例如:

假设我有 Mongo 藏书:

{author: "tolstoy", title:"war & peace", price:100, pages:800}
{author: "tolstoy", title:"Ivan Ilyich", price:50,  pages:100}

我想按作者对它们进行分组 - 对于每个作者,列出他的entire书籍对象:

{ 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" }
        }}

在这里找到:如何使用 mongodb 聚合并检索整个文档 https://stackoverflow.com/questions/22359742/how-to-use-mongodb-aggregate-and-retrieve-entire-documents

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Mongo分组和推送:推送所有领域 的相关文章

随机推荐