问题
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 :
- .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. - 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