antecessor
antecessor

Reputation: 2800

Error when running query using mongolite (R and MongoDB)

In my localhost y created a database (coches) and a collection (dtc) in MongoDB. My collection contains more than 2 million documents.

I would like to connect a subset of documents into R. The query I ran in MongoDB was the one of this question and I copy/paste here:

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

This subset resulted in 2265 documents.

I loaded the mongolite package in RStudio to connect MongoDB with R.

library(mongolite)
c <- mongo(collection = "dtc", db = "coches")

However, when I tried these queries:

# query 1
c$find('{
    "payload.fields.MDI_CC_DIAG_DTC_LIST": { $exists: true },
    "payload.asset": { $exists: true }
  }')

# query 2
c$find(query = '{
    "payload.fields.MDI_CC_DIAG_DTC_LIST": { $exists: true },
    "payload.asset": { $exists: true }
  }')

I get this error:

Error: Invalid JSON object: { "payload.fields.MDI_CC_DIAG_DTC_LIST": { $exists: true }, "payload.asset": { $exists: true } }

The original documents are JSON embedded files.

What's wrong in the coding? What am I missing?

Upvotes: 0

Views: 312

Answers (1)

antecessor
antecessor

Reputation: 2800

After a while, checking different places, I came across with the problem and therefore could be able to solve it. The problem was that $exists must be enclosed with quotation marks ("$exists"). So the code would be like this:

dtc$find('{ 
        "payload.fields.MDI_CC_DIAG_DTC_LIST" : { 
            "$exists" : true
        }, 
        "payload.asset" : { 
            "$exists" : true
        }
    }')

Upvotes: 0

Related Questions