Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass more than one criteria to Criteria.elemMatch() Api?

I have a situation that I want to provide 3 conditions in elemMatch method call provided by org.springframework.data.mongodb.core.query.Criteria Api.

Inventory collection looks like this -

{
    "_id" : "H-P3NCDST45"
    "booking" : [
    {
        "updateDate" : ISODate("2018-01-29T13:32:03.789Z"),
        "status" : "STARTED",
        "message" : "abc"
    },
    {
        "updateDate" : ISODate("2018-01-29T13:32:04.789Z"),
        "status" : "PENDING",
        "message" : "def"
    },
    {
        "updateDate" : ISODate("2018-01-29T13:33:04.789Z"),
        "status" : "CONFIRMED",
        "message" : "abc"
    }
]
}

I want to do something like below query. Fetch all documents from inventory collection which have at-least one embedded document in booking array whose status is "STARTED" and updateDate is between <start> and <end> date, i.e. Fetch all booking from inventory which are started/initiated between given <start> and <end> date.

db.inventory.find({"booking": { $elemMatch: { status: "STARTED",updateDate: { $gte: ISODate("2018-01-01T14:04:34.447Z"), $lte: ISODate("2018-01-20T14:04:34.447Z")}}}})

Criteria Api provides criteria.elemMatch(Criteria c). How to pass multiple criteria in this elemMatch(c) method call?

like image 419
doga Avatar asked Jan 29 '18 14:01

doga


1 Answers

You can try

Criteria criteria = 
   Criteria.where("booking").
   elemMatch(
      Criteria.where("status").is("STARTED").
      and("updateDate").gte(date1).lte(date2)
   );
like image 65
s7vr Avatar answered Nov 15 '22 11:11

s7vr