Trung Tran
Trung Tran

Reputation: 13721

How to return specific field's value in mongodb

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!

Upvotes: 0

Views: 5969

Answers (2)

Izzi
Izzi

Reputation: 2612

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

Upvotes: 1

JohnnyHK
JohnnyHK

Reputation: 311835

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.

Upvotes: 2

Related Questions