antecessor
antecessor

Reputation: 2800

Combining two $exists en MongoDB .find

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?

Upvotes: 1

Views: 311

Answers (2)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

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.

Upvotes: 1

Radosław Miernik
Radosław Miernik

Reputation: 4094

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" /* ... */

Upvotes: 1

Related Questions