mongodb Mongo group and push:推送所有字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22150205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:37:13  来源:igfitidea点击:

Mongo group and push: pushing all fields

mongodb

提问by Pelit Mamani

Is there an easy way to "$push" all fields of a document? For example:

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

Say I have a Mongo collection of books:

假设我有一本 Mongo 书集:

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

I'd like to group them by author - for each author, list his entirebook objects:

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

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

I can achieve this by explicitly pushing all fields:

我可以通过显式推送所有字段来实现这一点:

{$group: {
     _id: "$author",
     books:{$push: {author:"$author", title:"$title", price:"$price", pages:"$pages"}},
}}

But is there any shortcut, something in the lines of:

但是是否有任何捷径,例如:

// Fictional syntax...
{$group: {
    _id: "$author",
    books:{$push: "$.*"},
}}

回答by Jurjen Ladenius

You can use $$ROOT

您可以使用 $$ROOT

{ $group : {
            _id : "$author",
            books: { $push : "$$ROOT" }
        }}

Found here: how to use mongodb aggregate and retrieve entire documents

在这里找到:如何使用 mongodb 聚合并检索整个文档

回答by Neil Lunn

Actually you cant achieve what you are saying at all, you need $unwind

实际上你根本无法实现你所说的,你需要$unwind

db.collection.aggregate([
    {$unwind: "$books"},

    {$group: {
         _id: "$author",
         books:{$push: {
             author:"$books.author",
             title:"$books.title",
             price:"$books.price",
             pages:"$books.pages"
         }},
    }}
])

That is how you deal with arrays in aggregation.

这就是你在聚合中处理数组的方式。

And what you are looking for to shortcut typing all of the fields does not exist, yet.

并且您正在寻找的快捷方式键入所有字段尚不存在

But specifically because of what you have to do then you could notdo that anyway as you are in a way, reshaping the document.

但特别是因为你必须做的事情,你无论如何都不能这样做,因为在某种程度上,重塑了文档。

回答by Ivan.Srb

If problem is that you don't want to explicitly write all fields (if your document have many fields and you need all of them in result), you could also try to do it with Map-Reduce:

如果问题是您不想显式写入所有字段(如果您的文档有很多字段并且您需要所有这些字段),您也可以尝试使用 Map-Reduce 来完成:

db.books.mapReduce(
    function () { emit(this.author, this); },
    function (key, values) { return { books: values }; },
    { 
        out: { inline: 1 },
        finalize: function (key, reducedVal) { return reducedVal.books; } 
    }
)