Note that there are some explanatory texts on larger screens.

plurals
  1. POMongodb structure operation
    text
    copied!<p>Another day. Another Mongodb query. </p> <p>I wish to create the following structure in once of my collections: </p> <p><code>amitverma</code> is the user and the nested object is message's UTC timestamp. I want to push messages in the following structure.</p> <pre><code>{ "username" : "macbook", "messages" : { "amitverma" : { "1383321755" : { "to" : "macbook", "message" : "hi.", "sender" : "amitverma", }, "1383321712" : { "to" : "macbook", "message" : "hi.", "sender" : "amitverma", } } }, "_id" : ObjectId("5273d09ab743db7a5f000001") } </code></pre> <p>I cant use $push or $addToSet as it isnt an array. Or can I? </p> <p>Also, I have the following code right now: </p> <pre><code>var pushNotification = {}; var addon = {}; var anotheraddon = {}; var utcTime = arrayOps.encodeTime(); addon[data.sender] = []; anotheraddon[utcTime] = data; addon[data.sender].push(anotheraddon); // var a = pushNotification; // a.push(anotheraddon); // console.log(pushNotification); pushNotification['messages'] = {} pushNotification['messages'][data.sender] = []; pushNotification['messages'][data.sender] = data; var a = 'messages.' + data.sender + '.$'; console.log('push object'); console.log(pushNotification); co_notifications.update( {'username': data.to}, { $addToSet: pushNotification}, function(err, docs){ console.log(err); console.log(docs); if (docs == 0){ co_notifications.insert( {'username': data.to, 'messages': addon}, function(er, doc){ }); } }, {upsert: true} ); </code></pre> <p>Excuse the garbage code. The above code results in this structure: </p> <pre><code>{ "username" : "macbook", "messages" : { "amitverma" : [ { "1383321755" : { "to" : "macbook", "message" : "hi.", "sender" : "amitverma", } } ] }, "_id" : ObjectId("5273d09ab743db7a5f000001") } </code></pre> <p>which isn't exactly what I desire. </p> <p>Is there a way I can create the structure I want and also read and update from the same easily? Thanks. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload