简体   繁体   中英

mongodb find all records with subdocument id equals to

i have the following collection records:

> db.products.find(ObjectId("53a9a6aad901f2961403fc9b")).pretty()
{
    "_id" : ObjectId("53a9a6aad901f2961403fc9b"),
    "code" : "N39",
    "name" : {
        "en-UK" : "N39"
    },
    "weight" : [
        90
    ],
    "collectionId" : ObjectId("53a9a6a8d901f2961403fbe2"),
    "fabric_composition" : [
        {
            "fabricId" : ObjectId("53a9a6a9d901f2961403fc69"),
            "value" : 70
        }
        {
            "fabricId" : ObjectId("53a9a6a9d901f2961403fc6a"),
            "value" : 30
        }
    ],
    "visible" : "true",
    "manufacturer" : "53a859d9d901f2e8f81ac83b"
}

and

> db.fabric.find().pretty()
{
    "_id" : ObjectId("53a9a6a9d901f2961403fc69"),
    "name" : [
        {
            "en-UK" : "Recycled Organic Cotton"
        }
    ]
}
{
    "_id" : ObjectId("53a9a6a9d901f2961403fc6a"),
    "name" : [
        {
            "en-UK" : "Recycled Polyester"
        }
    ]
}

how do i query the mongodb collection products to list all products that have a fabric_composition with ObjectId for Recycled Organic Cotton as an example?

any advice much appreciated

You need to use use dot notation to query subdocuments:

db.products.find({
    "fabric_composition.fabricId" : ObjectId("53a9a6a9d901f2961403fc69")
});

This query will return all documents that have at least one sub-document with fabricId you're looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM