noizZze

MongoDB: Queries Against Arrays and Plain Fields

Did you know that with MongoDB you can easily run queries against fields that vary in type, like this?

> db.m.insert({ body: '1', phone_id: 1 })
> db.m.insert({ body: '2', phone_id: [ 1, 2 ]})

> db.m.find({ phone_id: 1 })
{ "_id" : ObjectId("4e56089fbdfcdc0f68c894ae"), "body" : "1", "phone_id" : 1 }
{ "_id" : ObjectId("4e5608afbdfcdc0f68c894af"), "body" : "2", "phone_id" : [ 1, 2 ] }

> db.m.find({ phone_id: 2 })
{ "_id" : ObjectId("4e5608afbdfcdc0f68c894af"), "body" : "2", "phone_id" : [ 1, 2 ] }

What’s curious is that when I query for “phone_id: 1”, it looks into the array of IDs as well as into the integer field. Quite a flexibility!

Amazingly, indexing is supported as well.