1

I have a mongodb structure like.

The structure of the place model

{.....
  amenities: [
    {
      name: "wifi",
      is_free: true
    },
    {
      name: "projector",
      is_free: false,
      price: "50"
    },
    ...........
    ...........
    ...........
  ]
.....}

I want to do a query where, I want to search for a place which is having some set of amenities exist in the place irrespective of the price & is_free fields. How can I do it inside the mongodb / mongoose query.

I want list of places which are having set of amenities like wifi and projector as a output.

Manish Kapoor
  • 488
  • 3
  • 16
Akhil P
  • 1,580
  • 2
  • 20
  • 29

3 Answers3

4
db.places.find({$and: [{'amenities.name': 'wifi'}, {'amenities.name':'projector'}])

It will find the places which have all amneties specified in an array ['wifi', 'projector'].

Hope it helps.

Manish Kapoor
  • 488
  • 3
  • 16
1

Try below query for one option of name:

db.places.find({amenities: {$exists: true}, 'amenities.name':'wifi'})

Also can try this query, if multiple options to check for name:-

var findQuery = {amenities: {$exists: true}, 'amenities.name':'wifi' , 'amenities.name':'projector'}

db.places.find(findQuery);

Hope this will help you.

Shrabanee
  • 2,706
  • 1
  • 18
  • 30
  • It doesn't solve my problem. Please have a look at multiple options it is resulting an empty array. Even my database is having matches with the query. – Akhil P Jun 24 '16 at 08:06
  • Updated the query as per your requirement. I think your question is not clear enough to let someone help you in one go. – Shrabanee Jun 24 '16 at 09:51
1

Please try executing following query

db.places.find({
    amenities : {
        $exist : true
    },
    amenities : {
        $elemMatch : {
            name : {
                $in : ['wifi', 'projector']
            }
        }
    }
})

In above mentioned query $exists operator will check for existence of amenities field in document and $elemMatch operator will match amenities array containing name field with following values

(1) wifi

(2) projector

profesor79
  • 9,213
  • 3
  • 31
  • 52
Rubin Porwal
  • 3,736
  • 1
  • 23
  • 26
  • 1
    have in mind that this will return only first matched element `elemMatch` specific :-) – profesor79 Jun 24 '16 at 07:24
  • 1
    It is returning documents which are matching at least one amenity in the `$in : ['wifi', 'projector']`. But I want documents which must have bothe `['wifi', 'projector']` – Akhil P Jun 24 '16 at 07:48