Home > Software engineering >  How to find a record by unique value inside an array in MongoDB?
How to find a record by unique value inside an array in MongoDB?

Time:02-08

I want to locate a record which has the "String to match" in his "affiliates.wallets" array. But for some reason, I'm unable to do it.

I was trying something like:

db.collection.findOne({ "affiliates.wallets": {$in: "[String to match]"}, (err, data) => console.log(err, data)})

But it returns null. So, I'm asking for help.

Simplified Wallet Schema:

Wallet {
  affiliates: {
    wallets: [String]
  }
}

P.S: I'm using findOne method because this "String to match" which I'm using to locate the record is unique and it can be located only in one record.

CodePudding user response:

You don't need $in operator. You can do it like this:

db.collection.findOne({
  "affiliates.wallets": "String to match", 
}, (err, data) => {
  console.log(err, data)
})
  •  Tags:  
  • Related