0

I have a collection in my DB where each item looks like this :

{
  "_id" : ObjectId("XXXXXX"),
  "name" : "foo",
  "products" : [{
      "name" : "bar",
      "code" : 123
   },{
      "name" : "foo",
      "code" : 321
   }]
}

And I want to get from a query a single array containing : [123, 321] from a specific collection.

This is what I have attempted :

  db.getCollection('catalog').aggregate({
        "$project": {
        "products": {
            "$map": {
                "input": "$products",
                "as" : "item",
                "in" : "$$item.code"
            }
        }
        }
    })

But it fails and it stats "Last stage is undefined".

What am I doing wrong?

Matias Barrios
  • 4,674
  • 3
  • 22
  • 49

1 Answers1

0

You can get a output like this, { "products" : [ 123, 321 ] }, using the following aggregation. Note the usage of the $reduce instead of the $map array operator.

db.collection.aggregate([
  { 
      $project: {
          _id: 0,
          products: { 
              $reduce: { 
                  input: "$products", 
                  initialValue: [],
                  in: { 
                      $concatArrays: [ "$$value", ["$$this.code"] ] 
                  } 
              }
          }
      }
  }
])
prasad_
  • 12,755
  • 2
  • 24
  • 36
  • I get this error when attempting this : { "ok" : 0, "errmsg" : "Aggregation project operator not supported: '$reduce'", "code" : 305 } : aggregate failed : – Matias Barrios Dec 07 '20 at 17:01
  • The above aggregation runs fine in `mongo` shell, and MongoDB v4.2.8. There are no errors. It is tested with the document you had posted. – prasad_ Dec 07 '20 at 17:48
  • Can you tell what is your working environment? What tools are you using and the MongoDB version? – prasad_ Dec 07 '20 at 17:50
  • Im working on MongoDB 3.6.0 and using Robo3T to test this – Matias Barrios Dec 07 '20 at 18:43
  • MongoDB v3.6 has the [$reduce](https://docs.mongodb.com/v3.6/reference/operator/aggregation/reduce/#reduce-aggregation) operator; it is valid to use it in an aggregation query. Also, the `$concatArrays` operator and the `$project` stage. The aggregation query I had posted works fine with MongoDB v3.6, also. – prasad_ Dec 08 '20 at 05:01