Note that there are some explanatory texts on larger screens.

plurals
  1. PONested document value search in MongoDB
    primarykey
    data
    text
    <p>Given the following user object in MongoDB, what would be the fastest way to search by <code>relation.$.status == 'friends'</code>?</p> <p>Need to find a way to <code>find</code> in a <code>user</code> collection's <code>relation</code> data that contains an object with a value of <code>"friends"</code> (see pseudo query below).</p> <p>The keys for this particular collection have been set to uids, so assume that the "<strong>User Data</strong>" section below may not be altered.</p> <p><strong>User Data:</strong></p> <pre><code>{ "_id": ObjectId('1a1a1a1a111a1a11a1a1a1a'), "name": "Tester", "relation": { "2b2b2b2b2b2b2b2b2b2b2b": { "status": 'friends', "status_changed_date: ISODate("2013-10-28T00:00:00.0000Z"), // etc... }, "3c3c3c3c3c3c3c3c3c3c3c": { "status": 'engaged', "status_changed_date: ISODate("2013-10-28T00:00:00.0000Z"), // etc... } } } </code></pre> <p><strong>Query:</strong></p> <pre><code>var query = { // pseudo, key-ignoring nested document search 'relation.$.status': 'friends' } var projection = { 'relation': 1 } db.user.findOne(query, projection) </code></pre> <p><strong>Desired Output:</strong></p> <pre><code>{ "2b2b2b2b2b2b2b2b2b2b2b": { "status": 'friends', "status_changed_date: ISODate("2013-10-28T00:00:00.0000Z"), // etc... } } </code></pre> <p>The obvious correction to the <em>User Data</em> structure should be making <code>relation</code> an array of objects of which contain <code>_id</code> and <code>status</code> as keys. Kinda looking for a temporary shim here.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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