0

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}}})

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Sorry, horses - Object
That comment doesn't seem to make any sense? If you're bound to model horses as an object, you're probably doing something wrong.
I already knew it possible to somehow change the field type Horses with an array object to 139,000 records
db.cards.find({"horses._id" : 609075}); - not working
Of course not, unless you change your model to an array as I pointed out in my answer. You should review the terms used in MongoDB (collections, array and documents) and change your data structure.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.