0

I have a collection in Mongo that contains documents that look like this:

{
    name: "Bob",
    destinations:
    [
        {
            city: "Dallas",
            state: "Texas",
            isBusiness: "true",
        }, {
            city: "San Diego",
            state: "California",
            isBusiness: "true",
        }   
    ]
},
{
    name: "Sue",
    destinations:
    [
        {
            city: "Las Vegas",
            state: "Nevada",
            isBusiness: "false",
        }, {
            city: "Sacramento",
            state: "California",
            isBusiness: "true",
        }   
    ]
}

I want to query this collection so that I receive the name of each person along with the city of each destination within the state of California, but not the isBusiness value which should be ignored.

The result of the query should be:

[
    {
        name: "Bob",
        city: "San Diago",
    },
    {
        name: "Sue",
        city: "Sacramento"
    }
]

This example is a bit contrived, but how do I do this?

3 Answers 3

1

Quite basic aggregation, not sure what to explain about it:

db.collection.aggregate([
    {$unwind: "$destinations"},
    {$match: {"destinations.state":"California"}},
    {$project: {_id:0, name: 1, city: "$destinations.city"}}
])

Docs:

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

Comments

0
db.collectionName.find({"destinations.state":"California"},{name:1,"destinations.city":1})

2 Comments

This is not quite right. It does correctly extract the city from the destinations array, but it still returns all the cities, not just the ones in California.
yep. the posted answer with aggregation is your solution.
0

$elemMatch operator of MongoDB is used to apply filter over an array of elements.

According to description as mentioned into above question please try find executing following find operation into MongoDB shell.

db.collection.find({
    destinations: {
        $elemMatch: {
            state: "California"
        }
    }
}, {
    'destinations.$': 1,
    name: 1,
    _id: 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.