3

Let's say I've got these values in database:

{
    name: '1',
    values: [{
        subname: 'awesome'
    }, {
        surname: 'cool'
    }]
}

how could I filter the array with only the value I'm interested in?

I would like to get as result of my find:

{
    name: '1',
    values: [{
        subname: 'awesome'
    }]
}

I thought maybe there is a possibility with select? Something like

MyCollection.find({name: '1'}).select(BLACK_MAGIC);

Where BLACK_MAGIC filters my array with the values I'm interested in, in this example values.subname = 'awesome'

Thx in advance for any ideas

Side note: I'm interesting to solve this with Mongoose queries and functions, not a solution with a post javascript on the resulting array

4
  • Maybe $elemMatch might be useful. Commented Jul 10, 2017 at 18:22
  • Thx @Mikey, look like you are right, the examples of the documentation seems to fit my needs...gonna study and try that! Commented Jul 10, 2017 at 18:25
  • @Mikey it kind of work but doesn't fulfill 100% what I'm looking for. Doing Collection.find({something}, {$elementMatch}) gonna return {_id, theElementMatched} but I would like to return {_id, everything else, theElementMatched} Commented Jul 10, 2017 at 18:46
  • I had my doubts about $elemMatch when I saw the examples. Commented Jul 10, 2017 at 20:16

1 Answer 1

2

I think you could use aggregation for this.

You would $unwind so that each values object is in a separate document.

Then filter the results with $match.

MyCollection.aggregate([
    {
        $unwind: '$values'
    },
    {
        $match: { 
            'values.subname': 'awesome'
        }
    },
    // EDIT
    {
        $group: {
            _id: '$_id',
            name: { 
                $first: "$name"
            },
            values: {
                $push: { subname: "$values.subname" }
            }
         }
    }
], function (err, results) {

});

If it works, you are little bit closer. The only thing is that values is an object, not an array of one object. You could probably use $group with $first to get desired result.

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

1 Comment

cool thx for the answer. aggregation and unwind as you described did the job!

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.