I have a collection of users, each of which may be subscribed to one or more services. Each service has some meta data, including the number of credits the user has for that service.
How can I find all of the user objects who have less than 50 credits for some service if I have no way of knowing what the service objects keys will be?
Conceptually, it would be something like this, which doesn't work:
db.users.find({services.*.credits : {$lt : 50}})
The users collection:
{ _id: 4f0ea25072139e4d2000001f, services : { a : { credits : 100, score : 2000 }, b : { credits : 200, score : 300 }, c : { credits : 10, score : 1300 } } }, { _id: 4f0ea25072139e4d2000001f, services : { f : { credits : 68, score : 14 }, q : { credits : 1000, score : 102 }, z : { credits : 59, score : 352 } } }
Another example of what I want to do, in case it's not clear here, is explained here: http://www.mongodb.org/display/DOCS/Advanced+Queries#comment-346075854
With this wildcard index, MongoDB indexes all fields for each document in the collection. If a given field is a nested document or array, the wildcard index recurses into the document/array and stores the value for all fields in the document/array. For an example, see Create a Wildcard Index on All Field Paths.
MongoDB uses the dot notation to access the elements of an array and to access the fields of an embedded document.
Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.
This is an actual answer to your question.
How you can find all of the user objects who have less than 50 credits for some service if you have no way of knowing what the service objects keys will be is as follows.
Use a $where query:
db.users.find({ $where: function () { for (var index in this.services) if (this.services[index].credits < 50) return this; } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With