S
S
Stanislav2018-03-28 14:31:11
MongoDB
Stanislav, 2018-03-28 14:31:11

Is it possible to simplify the query when fetching an array of ids?

I need to get an array of identifiers where the user is mentioned, I do it like this

return  Collection.aggregate([
        {
            $match: {
                likes: userId
            }
        }, {
            $group: {
                _id: null,
                ids: {
                    $addToSet: '$_id'
                }
            }
        
    }]).then(e => {
        return e[0].ids
    })

I want to get rid of return e[0].ids, is it possible to immediately spit out the required array when fetching? Maybe there is such a method in mongodb for this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daniil Lebedinsky, 2018-04-02
@ms-dred

You can write something along the lines of:

const [{ ids: idsArray }] = await Collection.aggregate([
        {
            $match: {
                likes: userId
            }
        }, {
            $group: {
                _id: null,
                ids: {
                    $addToSet: '$_id'
                }
            }
    }]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question