Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

mongoDB – find a specific result, with a document nested in different ways

I have a little problem with my command lines in MongoDB. Here is what one of my documents looks like :

{
    "id": "6249c4eb85a7563e673b4360",
    "collection": {
        "id": "6244099cb9ebc40007ac2ce3"
    },
    "characters": [
        {
            "id": "6244074ab9ebc40007ac2cf9"
        },
                {
            "id": "6244074ab9ebc40007ac2ce1"
        }
    ],
}

Then, in the MongoDB shell, I try to retrieve some books according to their criteria, here is an example :

db.comic.find({
    characters: {
        $elemMatch:{
            _id: {
                $in: [
                    ObjectId("6244074ab9ebc40007ac2ce5")
                ]
            }
        }
    },
    collection: {
        $elemMatch:{
            _id: {
                $in: [
                    ObjectId("6244099cb9ebc40007ac2cfb")
                ]
            }
        }
    }
}).pretty()

If I remove the "collection" part, I find the books related to the characters. However, if I put back the "collection" part, I have no result. I think it’s related to the fact that "collection" is not an array, but I don’t know how to solve this problem, knowing that the goal is to have several collections in the search, hence the "$elemMatch" and the "$in".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance for your help, have a nice day.

>Solution :

You need to use collection._id instead of collection:{$elemMatch:{_id since $elemMatch is for finding an object inside an array.

So your query should look like:

db.comic.find({
    characters: {
        $elemMatch:{
            _id: {
                $in: [
                    ObjectId("6244074ab9ebc40007ac2ce5")
                ]
            }
        }
    },
    "collection._id": {
                $in: [ObjectId("6244099cb9ebc40007ac2cfb")]
    }
}).pretty()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading