简体   繁体   中英

How to find data within embedded documents array using id mongodb?

I am using mongodb with nodejs to find data in embedded document. strange fact is query works in database but not in actual nodejs code.

here is my data object:

{
"_id" : ObjectId("5c65866488a1c53464e46dc7"),
"cat_lang" : [
    {
        "_id" : ObjectId("5c65866488a1c53464e46dc8"),
        "en" : "temp",
        "it" : "temp"
    }
],
"providers" : [
    {
        "_id" : ObjectId("5c65866488a1c53464e46dc9"),
        "provider_name" : "temp0",
        "url" : "http://uber.com",

    },
    {
        "_id" : ObjectId("5c65866488a1c53464e46dca"),
        "provider_name" : "temp1",
        "url" : "http://uber2.com",
    }
]}

I have tried these queries in the mongodb shell works perfectly fine.

db.sideservices.findOne({"_id" : ObjectId("5c65866488a1c53464e46dc7")},{providers: {$elemMatch: {"_id" : ObjectId("5c65866488a1c53464e46dca")}}})

AND

db.sideservices.find({"providers._id":ObjectId("5c65866488a1c53464e46dca")},{'providers.$':1})

But when using the same functions in nodejs, it returns the whole object instead document with the given id.

this.db.collection('sideservices').find({'providers':{'$elemMatch':{'_id':ObjectId('5c65866488a1c53464e46dca')}}}).toArray((err,res) => {...})

You can do this way

this.collection("sideservices").find({
  "providers": { "$elemMatch": { "_id": ObjectId("5c65866488a1c53464e46dca") } }
})
.project({
  "providers": { "$elemMatch": { "_id": ObjectId("5c65866488a1c53464e46dca") } }
})
.toArray((err,res) => {...})

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