0

I made some complex data with mongoose schema.
And I want to find it by some specific condition.
Here is my data that is sent by post.

{
    "clientID": "1234",
    "clientOrder": [{
      "cartNumber":0,
      "departure": {
        "pickUpTimeFrom": "2019-02-03T13:00",
        "pickUpTimeto": "2019-02-03T15:00"
      },
      "destination": {
        "pickUpTimeFrom": "2019-02-04T13:00",
        "pickUpTimeto": "2019-02-04T15:00"
      }
    },
    "clientID": "1234",
    "clientOrder": [{
      "cartNumber":1,
      "departure": {
        "pickUpTimeFrom": "2019-02-03T13:00",
        "pickUpTimeto": "2019-02-03T15:00"
      },
      "destination": {
        "pickUpTimeFrom": "2019-02-04T13:00",
        "pickUpTimeto": "2019-02-04T15:00"
      }
    }]
}


And I want to find a specific array by the condition of date at "cartNumber: 0".
So, I made this find "cartNumber:0".
But, it doesn't send any date.
And , I couldn't make date condition like "2019-02-03" of "departure" even.
Could you help me to make the correct code?

  const allInform = await Order.find({
      clientOrder: {
        $elemMatch: {
          cartNumber: 0,
        },
      },
    });
DD DD
  • 1,148
  • 1
  • 10
  • 33
  • Can you please clarify what you want to look for? – Tom Slabbaert Apr 24 '19 at 08:36
  • Sorry for less explanation. I will give a specific date like 2019-02-03. And I want to find if there is the data coincided of that date comparing to at 'pickUpTimeFrom' of 'departure' of 'cartNumber: 0'. – DD DD Apr 24 '19 at 09:10

1 Answers1

1

I'm not quite sure i understood your schema as it has some mistakes, But i'm assuming each client order can have more than 1 cart and that cart#0 is not necessarly at index 0 of the array. If any of these 2 assumptions are wrong this following query could be simplified.

 let results = await Order.aggregate([
        {
          $unwind: "$clientOrder"
        },
        {
          $match: {
              $and: [{'clientOrder.cartNumber': 0}, 
                   {'clientOrder.destination.pickUpTimeFrom': <DATE OBJECT>}]
           }
        }
        ]);

notice assuming you saved the dates as a Date object you cant query it as a string.

If your using mongoshell use ISODate, it looks like: ISODate("2018-07-05T07:15:09.703+0000")

If your using javascript you can create a new date object: new Date(""2018-07-05")

  • when your matching dates like this it has to be an EXACT match.
Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43