Note that there are some explanatory texts on larger screens.

plurals
  1. POMongoDB/Mongoid: Can one query for ObjectID in embedded documents?
    text
    copied!<p>For the record, I'm a bit of a newbie when it comes to Rails and MongoDB. </p> <p>I'm using Rails+Mongoid+MongoDB to build an app and I've noticed that Mongoid adds ObjectID to embedded documents for some reason. </p> <p>Is there any way to query all documents in a collection by ObjectID both the main documents and nested ones?</p> <p>If I run this command</p> <pre><code>db.programs.findOne( { _id: ObjectId( "4d1a035cfa87b171e9000002" ) } ) </code></pre> <p>I get these results which is normal since I'm querying for the ObjectID at root level. </p> <pre><code>{ "_id" : ObjectId("4d1a035cfa87b171e9000002"), "created_at" : "Tue Dec 28 2010 00:00:00 GMT+0000 (GMT)", "name" : "program", "routines" : [ { "name" : "Day 1", "_id" : ObjectId("4d1a7689fa87b17f50000020") }, { "name" : "Day 2", "_id" : ObjectId("4d1a7695fa87b17f50000022") }, { "name" : "Day 3", "_id" : ObjectId("4d1a76acfa87b17f50000024") }, { "name" : "Day 4", "_id" : ObjectId("4d1a76ecfa87b17f50000026") }, { "name" : "Day 5", "_id" : ObjectId("4d1a7708fa87b17f50000028") }, { "name" : "Day 6", "_id" : ObjectId("4d1a7713fa87b17f5000002a") }, { "name" : "Day 7", "_id" : ObjectId("4d1a7721fa87b17f5000002c") } ], "user_id" : ObjectId("4d190cdbfa87b15c2900000a") } </code></pre> <p>Now if I try to query with an ObjectID with one of the embedded document (routines) I get null like so. </p> <pre><code>db.programs.findOne( { _id: ObjectId( "4d1a7689fa87b17f50000020" ) } ) null </code></pre> <p>I know one can query embedded objects like so</p> <pre><code>db.postings.find( { "author.name" : "joe" } ); </code></pre> <p>but that seems a bit redundant if you get passed an ObjectID of some sort and want to find in what document that ObjectID resides. </p> <p>So I guess my question is this...</p> <p>Is it possible, with some method I'm not familiar with, to query by ObjectID and search the ObjectID's in the embedded documents?</p> <p>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