Home > Mobile >  MongoDB convert object to array and apply filter
MongoDB convert object to array and apply filter

Time:07-28

I would like to perform a query in MongoDB. Given a document like this, where the keys of the inner object are "random":

{
  "replies": {
    "abcdefgh4343daj": {
      date: 2022-07-27T14:47:10.025Z,  
    },
    "1235fsedfseaww": {
      date: 2022-06-27T14:47:10.025Z,
    },
    "u89ues89fes8fse": {
      date: 2022-08-27T14:47:10.025Z,
    },
  }
}

I would like to Query replies and return an Array of all the objects that their date is smaller than 2022-07-28T14:47:10.025Z:

[{name: "abcdefgh4343daj", date: 2022-07-27T14:47:10.025Z}, {name: "1235fsedfseaww", date: 2022-06-27T14:47:10.025Z}]

My idea was to apply first an aggregate with an $objectToArray and then apply a filter $lt to that result. But my problem is that I don't know how to perform $objectToArray when the object key is not known.

CodePudding user response:

db.collection.aggregate([
  {
    "$project": {
      "data": {
        "$objectToArray": "$replies"
      }
    }
  },
  {
    $unwind: "$data" //To access array elements
  },
  {
    $match: {
      "$expr": {
        "$lte": [
          "$v.date",
          ISODate("2022-07-28T14:47:10.025Z")
        ]
      }
    }
  }
])

Playground

Same idea has been translated into query.

You may need to group back to bring back original structure.

  • Related