How to find items in collection by string input?

Viewed 28

In my collection users I have a field registerDate in format ISODate(< string >). I need to send a request to MongoDB. I use vibe.d framework and this one can send only deserialized JSON string. So, the input date can be either "2021-02-28T21:00:00Z" or UNIX timestamp.

In detail:

Works:

db.users.find(
    {
        "registerDate":{
            "$gte": ISODate("2021-02-28T21:00:00Z"), 
            "$lt": ISODate("2021-10-31T21:00:00Z")
            }
    })

Doesn't work:

"$gte": {$date: "2021-02-28T21:00:00Z"}, 
"$lt": {$date:"2021-10-31T21:00:00Z"}

I also try:

db.users.aggregate([
    { "$project": {
        "registerDate": {
            "$gte": { "$toDate": "2021-01-07T23:39:49.178Z" },
            "$lt": { "$toDate": "2021-09-07T23:39:49.178Z" }
            }
        }
    }])

Then, I get the error:

"errmsg" : "Invalid $project :: caused by :: FieldPath field names may not start with '$'."

1 Answers

Try $expr expression operator to use aggregation operator in $match stage,

db.users.aggregate([
  {
    $match: {
      $expr: {
        $and: [
          {
            $gte: [
              "$registerDate",
              { $toDate: "2021-02-28T21:00:00Z" }
            ]
          },
          {
            $lt: [
              "$registerDate",
              { $toDate: "2021-10-31T21:00:00Z" }
            ]
          }
        ]
      }
    }
  }
])

Playground

Related