0

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.

1 Answer 1

1
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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I think it should be $data.v.date inside the $lte expression. Anyways, is there any way of returning this in a more readable format? Like an array with objects with a new key name and the other fields as is?
Well, I can do that just with a $project, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.