简体   繁体   中英

Mongo Index for which documents have a nested key?

I have objects that look like:

{
  ...
  sources: {
    source_1: { [metadata about source_1] },
    source_z: { [metadata about source_z] },
    source_a: { [metadata about source_a] }
  }
}

If a document has data from a source, the entry with that name exists. Otherwise it does not exist. eg this has only data from source_a:

{
  ...
  sources: {
    source_a: { [metadata about source_a] }
  }
}

What index can help me speed up looking for documents which have data from a given source? To be more precise, I don't care what data that source contributed, only that it is included (there is an entry with that key in the sources object).

Should I make an index for each source, eg {"sources.source_z": 1} ?

Want to be most efficient, so as to not index all the data in the source, just the existence of it.

I would change the structure of your document into following if your sources are many in the order of hundreds. Otherwise you have to create index for each source value which is not practical:

{
  ...
  sources: [
    {type: "source_1", data: {...}},
    {type: "source_z", data: {...}},
    {type: "source_a", data: {...}}
  ]
}

With this data structure I would create an index on sources.type field.

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