简体   繁体   中英

MongoDB Tags Key Indexing

Going over some of the tutorials I have found MongoDB: get documents by tags , it seems that most tags are created as list of items. In my schema I want dynamic tags (key-value pairs), so every item in the collection has a tags field like the following entry:

{"tags" : {"key1" : "value1", "key2", "value2"}}

However I'd like indexing on the keys inside the tags field. AFAIK, this is not possible (even with multikey indexes), since the keys can be arbitrary?

Will I need to migrate the schema to look like:

{"tags" : [{"key1" : "value1"}, {"key2" : "value2"}]}

If so would my index look like:

db.foo.ensureIndex({"tags" : 1})

As suggested here:

http://www.mongodb.org/display/DOCS/Using+Multikeys+to+Simulate+a+Large+Number+of+Indexes

Yes, you can index over an array of subdocuments as tags, but you always need to query for the complete sub-document. create the index as you stated above with

db.foo.ensureIndex({'tags': 1})

and query with:

db.foo.find('tags': {'key1': 'value1'}) 

This will use the index and return all documents that have that particular sub-document in their tags array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM