Combining two $exists en MongoDB .find

拥有回忆 提交于 2021-01-28 21:40:53

问题


I would like to find documents that contain some fields, by using $exists. In particular, I am interested in two fields: payload.fields.MDI_CC_DIAG_DTC_LIST and payload.asset.

If I want to find only documents that contain the first one, this is my query:

db.getCollection("dtc").find({"payload.fields.MDI_CC_DIAG_DTC_LIST": {$exists: true}}).count()

It gives me 2265 documents.

When I try to find documents that contain two fields (the ones described above), I use this code:

db.getCollection("dtc").find({"payload.fields.MDI_CC_DIAG_DTC_LIST": {$exists: true}}, {"payload.asset": {$exists: true}}, {multi: true})count()

It throws me an error:

Failed to retrieve documents

[coches.dtc@ localhost:27017 [direct]] : An error occurred while retrieving documents!

Stacktrace: 
|_/ java.lang.Exception: [coches.dtc@ localhost:27017 [direct]] : An error occurred while retrieving documents!
|____/ Illegal argument: Invalid number of arguments to find().

What am I coding wrongly?


回答1:


Your query has couple of issues, try below one :

db.getCollection("dtc")
  .find({
    "payload.fields.MDI_CC_DIAG_DTC_LIST": { $exists: true },
    "payload.asset": { $exists: true }
  })
  .count();

Issues :

  1. .find() would take two arguments .find({...},{...}) first one being filter (All filters against collection go here) & second one is projection (Which is used to either exclude or include certain fields from result documents). Here you're passing in 3 args. But in general when it comes to node.js 3rd one could be a callback function but it has nothing to do with actual query being executed on database.
  2. There is no such thing called {multi: true} on .find(). multi will be passed as 3rd option/arg to .update() operations in order to update multiple documents matching filtered criteria.



回答2:


That's just a typo. Instead of adding another property to your query, you've passed it as a second argument to find.

Try this:

/* ... */ true}}, {"payload.asset" /* ... */
/* ... */ true},   "payload.asset" /* ... */


来源:https://stackoverflow.com/questions/60869881/combining-two-exists-en-mongodb-find

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!