shivaramanaiyer
shivaramanaiyer

Reputation: 615

search mongodb document based on subdocument value

I am using mongoosejs and have a MongoDB schema as follows for the user:

{
"_id" : ObjectId("my local id"),
"gravatar" : "user gravatar",
"username" : "users username",
"displayName" : "Shivaraman I",
"provider" : "facebook",
"providerData" : {
    "accessToken" : "facebook access token",
    "work" : [
        user work history
    ],
    "verified" : true,
    "updated_time" : "2015-02-04T13:23:44+0000",
    "timezone" : 1,
    "name" : "Shivaraman Iyer",
    "locale" : "en_GB",
    "link" : "user link",
    "last_name" : "Iyer",
    "gender" : "male",
    "first_name" : "Shivaraman",
    "email" : "email on facebook",
    "education" : [
        facebook user education list
    ],
    "id" : "user's facebook id"
},
...
"lastName" : "Iyer",
"firstName" : "Shivaraman",
}

I want to search the user based on his/her facebook id in the providerData. I did a lot of search and only found the elemMatch method which works for array sub documents. But I need something that works for this format of subdocument.

Have been searching a lot and haven't found anything. Any help would be great.

Thank you

Upvotes: 1

Views: 81

Answers (2)

Laxmikant Dange
Laxmikant Dange

Reputation: 7688

Its very simple, you can use simple find() and you can directly pass the object location as key and its value as your projection.

In your case

db.collection.find({
  "providerData.id":id
});

This will give you result.

replace collection keyword with your collection name.

Upvotes: 0

PaulShovan
PaulShovan

Reputation: 2134

var query = collection.find(); 
query.where('providerData.id', id);

Then execute the query. It will solve the problem

Upvotes: 1

Related Questions