简体   繁体   中英

mongodb: collection.find with $in operator doesn't return anything

I have a problem with a mongodb query.

currently I perform

collection.find({ "history.data": { "key": "paymentStatus", "value": { 
$in: ["fail1", "fail2", "fail3", "fail4", "fail5", "fail6", "fail7", 
"blocked"] } } })

but it does not return me the desired objects, in fact it returns an empty array.

The structure of the object is as follows:

{history: {time: ... , data: [ {key: "paymentStatus", value: "fail1"}, ... ] }}

Is this the correct syntax for a nested mongodb find query?

The correct syntax for your query is the following:

collection.find({ 
  "history.data": { 
    $elemMatch: {
      "key":"paymentStatus", 
      "value": { $in: ["fail1","fail2","fail3","fail4","fail5","fail6","fail7", "blocked"]}
    }
  }
})

In case you only had one query criteria instead of two, you could write the following:

collection.find({ "history.data.key":"paymentStatus"})

But in your case you have two query criteria, so you need to use $elemMatch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM