javascript - How to match a document with the value of an object attribute in Mongodb -
i'm trying match document in mongodb:
my document model :
profile: { languages: [ {"name": "french", "level": 1}, {"name": "english", "level": 2}, {"name": "spanish", "level": 4} ] }
what (can) have search result set:
lang = ["french", "english"]; objlang = [ {name: "french"}, {name: "english"} ];
what need db.find() documents match @ least 1 of languages, example :
profile.languages.name = "french"
or
profile.languages.name = "english"
what mean if have french or english in option set, need users have element of languages array name match 1 of options, no matter level of languages.
so, unless i'm wrong, can't
db.find({"profile.languages": {$in: [{name: "french"}, {name: "english"}]});
how proceed ?
thanks lot.
david
actually, right:
db.collection.find({"profile.languages.name":{$in: ["french","english"]} })
since profile.languages
array of subdocuments, can call in 1 of subdocument's keys , subsequent query gets mapped subdocuments containing key.
however, without proper indexing, added .explain()
shows pretty ugly:
{ "queryplanner" : { "plannerversion" : 1, "namespace" : "test.languages", "indexfilterset" : false, "parsedquery" : { "profile.languages.name" : { "$in" : [ "english", "french" ] } }, "winningplan" : { "stage" : "collscan", "filter" : { "profile.languages.name" : { "$in" : [ "english", "french" ] } }, "direction" : "forward" }, "rejectedplans" : [ ] } }
(serverinfo
was ommited).
so in order make query efficient, need create index on field want query:
db.languages.ensureindex({"profile.languages.name":1})
an added explain tells matching documents identified via index:
{ "queryplanner" : { "plannerversion" : 1, "namespace" : "test.languages", "indexfilterset" : false, "parsedquery" : { "profile.languages.name" : { "$in" : [ "english", "french" ] } }, "winningplan" : { "stage" : "fetch", "inputstage" : { "stage" : "ixscan", "keypattern" : { "profile.languages.name" : 1 }, "indexname" : "profile.languages.name_1", "ismultikey" : true, "direction" : "forward", "indexbounds" : { "profile.languages.name" : [ "[\"english\", \"english\"]", "[\"french\", \"french\"]" ] } } }, "rejectedplans" : [ ] }, "ok" : 1 }
Comments
Post a Comment