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?
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.
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.
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.
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>, ... } }
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With