Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexing on a field which is in array of subdocuments

I'm trying to figure out the best design for the messaging system I'm porting from SQL Server to MongoDB - currently (in SQL Server) there are tree tables that store the message: Messages, Inbox and Sent. The message is stored in Messages table, and Inbox/Sent have entries for all recipients/senders for each message.

Now, in MongoDB I wanted to combine those three into one collection, with documents like this:

{
    _id: 
    subject:
    body:
    sender: {memid:, name:}
    recip: [{memid:, name:}, {memid:, name:}, {memid:, name:}, etc]

}

Now, I need to be able to retrieve all messages for a given recipient by memid and I have to do it fast, so an index is required (I will have hundreds of millions of such entries). So, my question is - can I index by a field of a document in an array?

like image 890
Andrey Avatar asked May 24 '11 01:05

Andrey


People also ask

Can you create an index on an array field in MongoDB?

To index a field that holds an array value, MongoDB creates an index key for each element in the array. These multikey indexes support efficient queries against array fields. Multikey indexes can be constructed over arrays that hold both scalar values [1] (e.g. strings, numbers) and nested documents.

Is it possible to generate an array index that is also an array?

Yes you can. You can create a compound index on { "a.x": 1, "a.z": 1 } The restriction where at most one indexed field can be an array also applies. Save this answer.

Which index is used to index the content store in array?

MongoDB uses multikey indexes to index the content stored in arrays. If you index a field that holds an array value, MongoDB creates separate index entries for every element of the array. These multikey indexes allow queries to select documents that contain arrays by matching on element or elements of the arrays.

How do I query an array element in MongoDB?

To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }


1 Answers

see here https://docs.mongodb.com/manual/indexes/#multikey-index

Index by a field of a document in an array is supported by mongodb.

Example:

{ addr.zip: 1 }
like image 138
guolijing Avatar answered Nov 15 '22 23:11

guolijing