C
C
cat_crash2016-05-01 18:31:54
MongoDB
cat_crash, 2016-05-01 18:31:54

Where is the error in the $elemMatch request?

View request

db.getCollection('mycollection').find({"tags.tourism":"hotel"})

returns what is expected, but if it is rewritten using $elemMatch - for some reason an empty result is returned
db.getCollection('mycollection').find({"tags":{$elemMatch:{"tourism":"hotel"}}})

It is necessary to use exactly $elemMatch. in the future, array pairs will be used for the search, for {"tourism":"hotel","building":"yes"}
example Document Example
{
    "_id" : ObjectId("56d37e89b10135ea7a45980f"),
    "timestamp" : "2016-02-28T22:53:42.597Z",
    "tags" : {
        "building" : "yes",
        "name" : "Amish View Inn & Suites",
        "tourism" : "hotel"
    },
    "type" : "adrpnt"
}

MongoDB version: 3.0.9

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rostislav Grigoriev, 2016-05-01
@cat_crash

Quotes should be removed
$elemMatch is not suitable for this structure here, because it works on the list, that is, it worked when the data was like this:

"tags" : [{
        "building" : "yes",
        "name" : "Amish View Inn & Suites",
        "tourism" : "hotel"
    }]

But if the list is not provided, then the following query is quite suitable for this task:
db.mycollection.find({"tags.tourism":"hotel", "tags.building":"yes"})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question