Using keys as values, like you do in:
'username1':['user1','user2','user3'],
is a bad idea as you can not do a indexed query where you look for documents that have a specific sender. This works:
db.messages.find( { 'username1' : { $exists: true } } );
But it is not going to be fast.
It is probably wise to keep your first option, with one document per message and sender. Then you can just do:
db.messages.find( { sender: 'username1' } );
Adding a new recipient to this document can be done with:
db.messages.update(
{ 'msgid' : '867896', sender: "username1" },
{ 'recipient': { $push: "user4" } }
);
You can make MongoDB use the same index for both queries as well, by having:
db.messages.ensureIndex( { sender: 1, msgid: 1 } );
Other hints
You need to be aware that you also can not have two documents with the same _id
value as you have in your first example. So you will have to make sure to add this ID as a different field than _id
. For example:
{
msgid:'3DA5FC203,
sender:'username1',
recipient:['user1','user2','user3']
},
And let MongoDB just create the _id
field for you.