Search code examples
ruby-on-railsmongodbmongoidmongoid3

MongoDB/Mongoid: search for documents matching first item in array


I have a document that has an array:

{
    _id: ObjectId("515e10784903724d72000003"),
    association_chain: [
        {
            name: "Product",
            id: ObjectId("4e1e2cdd9a86652647000003")
        }
    ],
    //...
}

I'm trying to search the collection for documents where the name of the first item in the association_chain array matches a given value.

How can I do this using Mongoid? Or if you only know how this can be done using MongoDB, if you post an example, then I could probably figure out how to do it with Mongoid.


Solution

  • Two ways to do this:

    1) if you already know that you're only interested in the first product name appearing in "association_chain", then this is better:

    db.items.find("association_chain.0.name":"something")
    

    Please note that this does not return all items, which mention the desired product, but only those which mention it in the first position of the 'association_chain' array.

    If you want to do this, then you'll need an index:

    db.items.ensureIndex({"association_chain.0.name":1},{background:1})
    

    2) if you are looking for a specific product, but you are not sure in which position of the association_chain it appears, then do this:

    With the MongoDB shell you can access any hash key inside a nested structure with the '.' dot operator! Please note that this is independent of how deeply that key is nested in the record (isn't that cool?)

    You can do a find on an embedded array of hashes like this:

    db.items.find("association_chain.name":"something")
    

    This returns all records in the collection which contain the desired product mentioned anywhere in the association_array.

    If you want to do this, you should make sure that you have an index:

    db.items.ensureIndex({"association_chain.name":1},{background: 1})
    

    See "Dot Notation" on this page: http://docs.mongodb.org/manual/core/document/