Qasim
Qasim

Reputation: 9648

How to to fetch embedded data from mongodb using query?

I have embedded data of user in authentication token schema and i want to fetch the token on the basis of username/email.

My json is in database is :

{
    "_id" : ObjectId("556573e744ae59c06a45533e"),
    "_class" : "com.samepinch.domain.user.AuthenticationToken",
    "token" : "c19f368e-8734-4a17-970e-e60e77dd955b",
    "user" : {
        "_id" : ObjectId("556566ca44ae69d5428778c5"),
        "age" : 0,
        "username" : "[email protected]",
        "firstName" : "Qasim",
        "lastName" : "Siddiqui",
        "email" : "[email protected]",
        "gender" : "male",
        "createdDate" : ISODate("2015-05-27T06:40:10.871Z"),
        "updatedDate" : ISODate("2015-05-27T06:40:10.871Z")
    }
}

Upvotes: 0

Views: 62

Answers (2)

Vishwas
Vishwas

Reputation: 7067

If you want only token as output you should add it in projection by matching criteria. As you want to match username and email in user object you can use following query :

db.collection.find({
    "user.username": "[email protected]",
    "user.email": "[email protected]"
  }, {
    "token": 1
})

If you want to match username or email in user object you can use -

db.collection.find({
$or: [{
        "user.username": "[email protected]"
       }, {
        "user.email": "[email protected]"
     }]
    }, {
    "token": 1
})

Upvotes: 1

llrs
llrs

Reputation: 3397

If I understood correctly you can do this:

collection.find_one({"user.username": "[email protected]",
                     "user.email":"[email protected]"},
                    {"token": 1, "_id": 0})
{"token": "c19f368e-8734-4a17-970e-e60e77dd955b"}

I am used to query it through pymongo (the python interface) so you may need to change the query a little bit.

What you need to known is the dot notation to query subdocuments

Upvotes: 0

Related Questions