Joum
Joum

Reputation: 3245

How to form mongoose query for $all in array

Given this collection:

    [{
        "users": [{
            "name": "one"

        }, {
            "name": "two"

        }]
    }, {
        "users": [{
            "name": "one"

        }, {
            "name": "three"

        }]
    }, {
        "users": [{
            "name": "fifteen"

        }, {
            "name": "one"

        }]
    }]

How can I query this using values (ie, "one" and "two") so that the findOne method returns only the document that has both "name":"one"and "name":"two" (order not relevant)? The users array will always have 2 elements, no more, no less.

I was trying something along the lines of:

Collection.findOne({"users":{$all:["one", "two"]}})

But it isn't working. Can anyone help?

EDIT: Latest attempt:

Collection.findOne({"users":{"name": {$all:["one","two"]}}})

Upvotes: 2

Views: 233

Answers (2)

tedcurrent
tedcurrent

Reputation: 431

Try this one:

{"users": {$all: [{"name": "one"}, {"name": "two"}]}}

Or use dot notation as proposed by JohnnyHK.

See here how $all is used: https://docs.mongodb.org/manual/reference/operator/query/all/

EDIT: Data was changed.

Upvotes: 1

JohnnyHK
JohnnyHK

Reputation: 312075

You can do this by using dot notation to identify a specific field within the array to which the $all operator should be applied:

Collection.findOne({'users.name': {$all: ['one', 'two']}})

Upvotes: 1

Related Questions