Indexing of Object keys in MongoDB
I have this structure
{
"_id": "willwill",
"rental": {
"hitchhikergalaxy": {[...]},
"animalfarm": {[..]}
}
}
Which [..]
is a embedded document storing the details of the rental (and the exactly same data also exists on another collection) and the rental
Object's keys are _id
of the book
collection.
How do I ensureIndex()
this query?
db.users.find({"rental.animalfarm": {'$exists': true}})
(I use MongoDB on PHP, but the example above is in JavaScript)
You might want to think about refactoring the document such that:
"rental":
[
{ "name":"hitchikergalaxy", "attributes": { your stuff } },
{ "name":"animalfarm", "attributes": { your stuff } }
]
Now you have a path to ensureIndex "rental.name"
You can further find all documents where any user rented animalfarm using:
db.users.find( { "rental.name": "animalfarm" } )
I've been down the path of using data as keys/names -- and it always seems to make things more complicated than they need to be.
精彩评论