Home > Blockchain >  Is it possible to select data where date is in an array of date in mongoDB?
Is it possible to select data where date is in an array of date in mongoDB?

Time:12-19

I have an array of object like this return to mongoDB server.

[{"key":"demo_date","value":["2022-12-11T08:00:00.000Z","2022-12-12T08:00:00.000Z"...]}]

And query object like this

queryObj = {
      $and: [
        { deleted: false },
        {$or: []}
      ]
};

And I use this query object for the find method to get data from collection.

let data = await this.demoModel.find(queryObj, (err: Error) => {})

My question is how can I modify the queryObj such that the result would find all data with demo_dates as key and the value is in value array?

The record sample are like this

{
  _id: ObjectId('574168516'),
  demoLayer1: {
      demo_date: '2022-08-18T14:20:00.000Z',
      decoyDate: '2022-08-19T14:20:00.000Z',
  }
}

CodePudding user response:

You can use the $in operator to match a value within an array of possible values:

The $in operator selects the documents where the value of a field equals any value in the specified array.

db.collection.find({
  $and: [
    {
      //deleted: false,
      "demoLayer1.demo_date": {
        $in: [
          "2022-12-11T08:00:00.000Z",
          "2022-12-12T08:00:00.000Z",
          "2022-08-18T14:20:00.000Z"
        ]
      }
    }
  ]
})

Demo: https://mongoplayground.net/p/CH-MhcMrKOT

  • Related