Ruby-on-rails – MongoDB/Mongoid: Can one query for ObjectID in embedded documents

mongodbmongoidruby-on-rails

For the record, I'm a bit of a newbie when it comes to Rails and MongoDB.

I'm using Rails+Mongoid+MongoDB to build an app and I've noticed that Mongoid adds ObjectID to embedded documents for some reason.

Is there any way to query all documents in a collection by ObjectID both the main documents and nested ones?

If I run this command

db.programs.findOne( { _id: ObjectId( "4d1a035cfa87b171e9000002" ) } )

I get these results which is normal since I'm querying for the ObjectID at root level.

{
    "_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")
}

Now if I try to query with an ObjectID with one of the embedded document (routines) I get null like so.

db.programs.findOne( { _id: ObjectId( "4d1a7689fa87b17f50000020" ) } )
null

I know one can query embedded objects like so

db.postings.find( { "author.name" : "joe" } );

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.

So I guess my question is this…

Is it possible, with some method I'm not familiar with, to query by ObjectID and search the ObjectID's in the embedded documents?

Thanks.

Best Answer

You can't query ObjectIDs globally like that. You would have to do

db.programs.find({"routines._id": ObjectId("4d1a7689fa87b17f50000020")})

Related Topic