Wilker
Wilker

Reputation: 651

Mongdb query multiple value in different docs

How could query multiple value in one collection?

const user = db.collection('users').findOne({ username: 'john' })
const user = db.collection('users').findOne({ email: '[email protected]' })

Below are some dummy data. i hope could query name john and email docs in one line of code.

[{id:1, username: 'john', email: '[email protected]'},{id:2, username: 'kelvin', email: '[email protected]'}, {id:3, username: 'angle', email: '[email protected]'}]

Return Data Are: only id: 1 and 2. becasue they match the query

    [{id:1, username: 'john', email: '[email protected]'},{id:2, username: 'kelvin', email: '[email protected]'}]

Upvotes: 0

Views: 37

Answers (1)

J.F.
J.F.

Reputation: 15187

You can use $or operator in this way:

db.collection.find({
  "$or": [
    {
      "username": "john"
    },
    {
      email: "[email protected]"
    }
  ]
})

So you will find a document which matches username or email.

Exmaple here

Upvotes: 2

Related Questions