Nguyen
Nguyen

Reputation: 31

Find or Query Mongodb Data with logical conditions AND

My Mongo data like this

{
    "_id" : "5a5ffef0869422169c7aa01b",
    "email" : "[email protected]", 
    "checkin" : "2018-2-28 5:12",
    "checkout" : "2018-2-28 6:12",
}

I have 2 arrays:

  1. checkin : ['2018-2-28 5:12','2018-2-28 5:13','2018-2-28 5:14']
  2. checkout : ['2018-2-28 6:12','2018-2-28 6:13','2018-2-28 6:14']

And my query to find email.

db.getCollection('test').find({checkin : {$in: checkin}}, {"email": 1, "_id": 0})

I got result

[email protected] [email protected]

Now, I got a problem. I want to find email got checkin AND checkout. It's mean only find email have value in checkin - checkin array AND checkout - checkout array

I tried this query but not ok

db.getCollection('test').find({checkin : {$in: checkin}},{checkout : {$in: checkout}}, {"email": 1, "_id": 0})

Upvotes: 1

Views: 73

Answers (1)

fatimasajjad
fatimasajjad

Reputation: 601

db.getCollection('test').find(
 { $and: [
          {'checkin' : {$exists: true}},
          {'checkout' : {$exists: true}} 
        ] 
},
{
  'email':1
//just set email:1 to get only email in projection
})

This qyery returns email if 'checkin' AND 'checkout' both arrays exist. Just in case you want to check size of array you can use

'checkin':{ $size:{ $gt:1 } } 

Upvotes: 1

Related Questions