fuzzybabybunny
fuzzybabybunny

Reputation: 5254

How to return the value of a nested key in MongoDB?

The collection is called "baseCharges"

{
    photos: {
        under1500: 100,
        between1501_2000: 125,
        between2001_3000: 150,
        between3001_4000: 175,
        between4001_5000: 275,
        between5001_6000: 375,
        between6001_7000: 475,
        between7001_8000: 575,
        between8001_9000: 675,
        between9001_10000: 775,
        between10001_11000: 875
    },
    twilights: {
        under1500: 100,
        between1501_2000: 125,
        between2001_3000: 150,
        between3001_4000: 175,
        between4001_5000: 275,
        between5001_6000: 375,
        between6001_7000: 475,
        between7001_8000: 575,
        between8001_9000: 675,
        between9001_10000: 775,
        between10001_11000: 875
    },
    _id: "B8RCdQp8kuL9r6KdT"
}

All I want to return is the value for baseCharges.photos.under1500

I want to query the keys and have it return "100" as a value that I can then store in a variable, not as a pointer.

I've checked the other threads here on MongoDB but nothing is working for me.

db.baseCharges.find({ "photos.under1500" : 1 })

doesn't work.

db.baseCharges.find("photos.under1500")

doesn't work.

db.baseCharges.findOne({"photos.under1500" : 1 })

is null

Upvotes: 0

Views: 518

Answers (2)

Joachim Isaksson
Joachim Isaksson

Reputation: 180887

You seem to be close. I'm not quite sure what you mean by the value return so this may be answering the wrong question, but you can get the desired data just adding an (in this case) empty condition to your find. Your existing query is missing the search criteria part.

db.baseCharges.find({}, { _id:0, "photos.under1500" : 1 })

That will return the field you want (with no condition, that is for all entries)

EDIT: If you want a single value (from the first/single result row), you'll need to get the first document from the cursor find() returns, and use dot notation to get what you need;

db.baseCharges.find().next().photos.under1500

Upvotes: 2

fuzzybabybunny
fuzzybabybunny

Reputation: 5254

I found another way to do it.

This collection baseCharges only has one entry, so the following code worked:

db.baseCharges.findOne().photos.under1500

My issue is that I'm not used to the MongoDB way of working for a single item.

I know that with collections having multiple entries I have to first do a find by an _id or a unique combination of criteria to start drilling down the data.

But since this collection only has one entry, I figured that I could just use a straight heirarchical way of doing it. There's only one entry. An ID shouldn't be needed, so I thought simply doing db.baseCharges.photos.under1500 would do.

BUT that's not the way it works. Even when there is only one entry in a collection, you still have to find it and then drill down into the data you want.

Upvotes: 0

Related Questions