开发者

Indexing of Object keys in MongoDB

开发者 https://www.devze.com 2023-04-13 08:36 出处:网络
I have this structure { \"_id\": \"willwill\", \"rental\": { \"hitchhikergalaxy\": {[...]}, \"animalfarm\": {[..]}

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.

开发者_Go百科

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号