php - Querying for key in array -
my document construction looks this:
{ "_id": objectid("123781236712"), "statistic": { "1": { "key1": "value1", "key2": "value2", (...) }, "5": { "key1": "value1", "key2": "value2", (...) } } }
i'm trying compose find gives me documents contains statistic.5
, no matter whats content of "5".
so far, tried without success:
db.statistics.find({"statistic": {$elemmatch: {$in:["5"]}}}) db.statistics.find({"statistic": {$elemmatch: "5"}})
thanks in advance!
i'm trying compose find gives me documents contains statistic.5, no matter whats content of "5".
for exact question (with current document structure), query posted work perfectly:
db.statistics.find({"statistic.5":{$exists:true}});
your query looks if key exists in document , asked in question.
however, current document construction isn't practical queries (that's neil suggesting in answer) , there alternative way organize document construction that's more flexible , easier query using mongodb.
i'm going suggest different construction neil's:
{ "_id": objectid("..."), "statistic": [ { "key1": "value1", "key2" : "value2" }, { "key1": "value3", "key2" : "value4" }, { "key1": "value5", "key2" : "value6" } /* etc ... */ ] }
creating array of subdocuments (instead of creating object hashed key-value pairs) enable next queries on document.
this equivalent query (and you're looking for):
db.coll.find({"statistic.5" : { $exists : 1}});
you can check size of array (if array contains x items):
db.coll.find({"statistic" : { $size : 5}});
and can search if any of subdocuments contains key specific value (which current construction doesn't support):
db.coll.find({"statistic.key1" : "value3");
php mongodb mongodb-query
No comments:
Post a Comment