user3603475
user3603475

Reputation: 57

Find document in subarray in mongodb

I have many collections such this

{
"_id" : 383566,
"horses" : {
    "609075" : {
        "_id" : 609075,
        "name" : "Aghawonan"
    },
    "634478" : {
        "_id" : 634478,
        "name" : "French Thyne"
    },
    "595535" : {
        "_id" : 595535,
        "name" : "Doctor Hanley"
    },
    "593718" : {
        "_id" : 593718,
        "name" : "Ballyhill Boy"
    },
    "578089" : {
        "_id" : 578089,
        "name" : "Oh Alabama"
    },
    "632597" : {
        "_id" : 632597,
        "name" : "Bowling Alone"
    },
    "525424" : {
        "_id" : 525424,
        "name" : "Tally-Ho Duke"
    }
}

I need to find all the collections in the array where Horses _id have match

My version, but it does not work

db.cards.find({'horses': {$elemMatch: {_id:525424}}})

Upvotes: 0

Views: 143

Answers (1)

mnemosyn
mnemosyn

Reputation: 46311

in your example, horses is not an array, but an object. This data structure is a bit odd and redundant because the id is both part of the 'name' (or path if you will) and the actual document data. In your data structure, you could refer to a particular horse by horses.609075.name, but that is usually not very helpful.

Your query would work if horses were an array like so:

{
  "_id" : 383566,
  "horses" : [
    {
        "_id" : 609075,
        "name" : "Aghawonan"
    },
    {
        "_id" : 634478,
        "name" : "French Thyne"
    },
    // ...
   ]
 }

Since you're only querying for a single property, the $elemMatch isn't required. You could simply query like this:

db.cards.find({"horses._id" : 609075});

Please note that you'll receive the entire card as a result, not just a part of the array.

As a side note, why are the ids of the horses called _id? The name _id is a special field only at the root level. Embedded documents don't have any special fields.

Upvotes: 1

Related Questions