Mongo group and push: pushing all fields

后端 未结 3 409
走了就别回头了
走了就别回头了 2020-11-29 22:07

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

Say I have a Mongo collection of books:

{author: \"tolstoy\", title:\"war &a         


        
相关标签:
3条回答
  • 2020-11-29 22:41

    Actually you cant achieve what you are saying at all, you need $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 not do that anyway as you are in a way, reshaping the document.

    0 讨论(0)
  • 2020-11-29 22:51

    You can use $$ROOT

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

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

    0 讨论(0)
  • 2020-11-29 23:00

    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:

    db.books.mapReduce(
        function () { emit(this.author, this); },
        function (key, values) { return { books: values }; },
        { 
            out: { inline: 1 },
            finalize: function (key, reducedVal) { return reducedVal.books; } 
        }
    ) 
    
    0 讨论(0)
提交回复
热议问题