Home > Net >  mongoDB - find a specific result, with a document nested in different ways
mongoDB - find a specific result, with a document nested in different ways

Time:04-22

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".

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

CodePudding user response:

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()
  • Related