Home > Software design >  Getting item in a nested array mongoldb
Getting item in a nested array mongoldb

Time:08-20

I am trying to aggregate an object but getting null. Would appreciate help.

here is my sample object

[
  {
    "_id": 1,
    "item": "sweatshirt",
    "price.usd": 45.99,
    "am": [
      {
        "one": 100
      }
    ],
    qty: 300
  },
  {
    "_id": 2,
    "item": "winter coat",
    "price.usd": 499.99,
    "am": [
      {
        "one": 50
      }
    ],
    qty: 200
  },
  {
    "_id": 3,
    "item": "sun dress",
    "price.usd": 199.99,
    "am": [
      {
        "one": 10
      }
    ],
    qty: 250
  }
]

This is my query

db.collection.aggregate([
  {
    $group: {
      _id: {
        $getField: {
          $literal: "am.one"
        }
      },
      
    }
  }
])

currently I am getting

[
  {
    "_id": null
  }
]

any help is appreciated.

I want my response to look like

{

_id: 1
anotherThin: anotherValue
}

CodePudding user response:

Here's one way you could do it.

db.collection.aggregate([
  { // only pass docs that have a numerical "am.one"
    "$match": {
      "am.one": {"$type": "number"}
    }
  },
  { // unwind in case multiple objects in "am"
    "$unwind": "$am"
  },
  { // group by "id" and average "one" values
    "$group": {
      "_id": "$am.id",
      "am1avg": {"$avg": "$am.one"}
    }
  }
])

Try it on mongoplayground.net.

  • Related