1

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) => {...})

1 Answer 1

1

You can do this way

this.collection("sideservices").find({
  "providers": { "$elemMatch": { "_id": ObjectId("5c65866488a1c53464e46dca") } }
})
.project({
  "providers": { "$elemMatch": { "_id": ObjectId("5c65866488a1c53464e46dca") } }
})
.toArray((err,res) => {...})
Sign up to request clarification or add additional context in comments.

3 Comments

Hi @Anthony Winzlet if you see my question I have already tried this approach for some reason it doesn't fetch the exact document but fetches whole object. What I mean is from "_id" : ObjectId("5c65866488a1c53464e46dc7"), to end. What is required to get a single document only of this Id --> "_id" : ObjectId("5c65866488a1c53464e46dca") thanks
This is something different. Try the above answer with you nodejs code. Then I will let you know the issue
Hi thanks man you are a life saver !! I have spent whole day on it but that worked like charmed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.