Search code examples
node.jsmongodbmongodb-compass

Mongodb select information to get from an object without knowing object key


I have this documents at my DB

{
"_id":"606b583b2506eb000988a8fd",
"lastSync":"2021-04-13T00:10:02.984+00:00",
"Month":{
    "2020-12":{
      "a":10,
      "b":21
    },
    "2021-01":{
      "a":112,
      "b":34
    },
    "2021-03":{
      "a":35,
      "b":56
    },
    "2021-02":{
      "a":767,
      "b":56
    },
    "2021-04":{
     "a":78,
     "b":98
   }
}
}

How can I query something like db.collection.agreggate(query) and get as answer an array like:

[
"2020-12":{
"a":10},
"2021-01":{
"a":112},...]

Have already tried agregation methods with $project but just could not find the kind of object I wanted


Solution

  • Demo - https://mongoplayground.net/p/v5My6yjrIC0

    $map

    $replaceRoot

    $arrayToObject

    $objectToArray

    db.collection.aggregate([
      {
        $replaceRoot: {
          "newRoot": {
            $arrayToObject: { // convert array to object
              $map: { // loop over each item in an array and returns an array
                "input": { $objectToArray: "$Month"}, // convert to array
                "as": "el",
                "in": { k: "$$el.k", v: { a: "$$el.v.a" } // shape the data
                }
              }
            }
          }
        }
      }
    ])
    

    If you want everything inside Month check this demo - https://mongoplayground.net/p/lD0wPTc_W4Y

    db.collection.aggregate([
      {
        $replaceRoot: {
          "newRoot": "$Month"
        }
      }
    ])