0

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")
    }
}

2 Answers 2

1

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
})
Sign up to request clarification or add additional context in comments.

7 Comments

i also want to write cutome query in repository using @Query . Can you help me in this
@Qasim sure. but didn't get your question. can u update it in your question please?
Thanks for replying @vishwas . I am using @Query("{'user.id' : ?0}") AuthenticationToken findByUserId(String userId); but not getting AuthenticationToken object from mongodb
@Qasim. Still it is pretty unclear about what you are saying. Which driver/language you are using? Do you want to convert this query using any other mongo driver. Please add more description. If you want to match with object id, use db.collection.find({"_id":ObjectId("add mongoId here")},{"token": 1})
I am using spring with mongodb and i have built mongo repository in which i have write my custom query mentioned above.
|
0

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

Comments

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.