0

how can I return a specific value for a specific document in MongoDB? For example, I have a schema that looks like:

{
"_id" : "XfCZSje7GjynvMZu7",
"createdAt" : ISODate("2015-03-23T14:52:44.084Z"),
"services" : {
    "password" : {
        "bcrypt" : "$2a$10$tcb01VbDMVhH03mbRdKYL.79FPj/fFMP62BDpcvpoTfF3LPgjHJoq"
    },
    "resume" : {
        "loginTokens" : [ ]
    }
},
"emails" : {
    "address" : "[email protected]",
    "verified" : true
},
"profile" : {
    "companyName" : "comp1",
    "flagged" : true,
    "phoneNum" : "7778883333"
}}

I want to return and store the value for profile.flagged specifically for the document with _id : XfCZSje7GjynvMZu7. So far I have tried:

db.users.find({_id:'myfi3E4YTf9z6tdgS'},{admin:1})

and

db.users.find({_id: 'myfi3E4YTf9z6tdgS'}, {profile:admin});

I want the query to return true or false depending on the assigned value.

Can someone help? Thanks!

1
  • Yes, something like that. I want it to return "true" or "false" depending on the value Commented Mar 25, 2015 at 13:58

2 Answers 2

2

MongoDB queries always return document objects, not single values. So one way to do this is with shell code like:

var flagged =
   db.users.findOne({_id: 'myfi3E4YTf9z6tdgS'}, {'profile.flagged': 1}).profile.flagged;

Note the use of findOne instead of find so that you're working with just a single doc instead of the cursor that you get with find.

Sign up to request clarification or add additional context in comments.

Comments

1

The correct answer here is the method .distinct() (link here)

Use it like this:

db.users.find({_id:'myfi3E4YTf9z6tdgS'},{admin:1}).distinct('admin')

The result will be: 1 or 0

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.