mongodbfindarrayobject

find a document with a field inside an array of object


I have to find a document using findOne. The criteria is two things, one of them is normal and second one is an array of object. I want to check a field of the objectes inside the array.

{
    "_id" : ObjectId("62fa39a33ce0ba44db13ded3"),
    "user" : "62fa3876a5b7da972d2b9402",
    "product" : [
        {
            "id" : "62fa3349eb51e45b0df43567",
            "quantity" : NumberInt(1)
        }
    ]
}
{
    "_id" : ObjectId("62fa3fe6c5bc27da3da45364"),
    "user" : "62fa3fd6c5bc27da3da45363",
    "product" : [
        {
            "id" : "62fa3349eb51e45b0df43567",
            "quantity" : NumberInt(1)
        }
    ]
}

My collection is this. And I want to find a document by the user field and id field inside product array.

This is a small thing, I try a lot. But, Unfortunately I didn't get the code. Please help some one who know.


Solution

  • Try with:

    findOne({ user: <user_id>, 'product.id': <product_id> })