2

Is there a way to use jsonpath in mongodb 3.4/3.6? Sample is shown below , as in reference link JSON path parent object, or equivalent MongoDB query :

 var t1 = db.runCommand({aggregate : 'news_feeds',
pipeline:[],

cursor : {batchSize : 10}});
     t1.cursor.firstBatch.forEach(function(doc)
   {
var json = tojson(doc);
var json1="$.feeds.reviews[*].name"
var result = jsonPath(json, json1);
print(result);
  })

This query gives an error that jsonPath is not defined, but this jsonpath is there in the javascript

Please help

regards

kris

chiku
  • 485
  • 2
  • 8
  • 23
  • That error is because MongoDB shell doesn't recognize `jsonPath` as a function. MongoDB does not currently support jsonPath. – kevinadi Mar 05 '18 at 05:34
  • is there a alternate way to use jsonpath in mongodb? – chiku Mar 05 '18 at 18:18
  • Even I installed json-path using npm, and tried to execute,it says require is not defined, please help var jpath = require('json-path'); var t1 = db.runCommand({aggregate : 'news_feeds', pipeline:[], cursor : {batchSize : 10}}); t1.cursor.firstBatch.forEach(function(doc) { var json = tojson(doc); var res = jpath.resolve(json, "$.feeds.reviews[*].name") print(res); }) – chiku Mar 05 '18 at 19:00
  • `npm` and MongoDB shell are two different things. `npm` is for node. The only similarity between the two is that both uses Javascript as a language. I'm not familiar with how jsonPath was implemented, but there _may_ be a method to execute the jsonPath package inside the `mongo` shell, but MongoDB itself never support the use of jsonPath. – kevinadi Mar 06 '18 at 01:23

2 Answers2

3

Solved by using mongodb-shell-extensions https://www.npmjs.com/package/mongodb-shell-extensions#jsonpath works pretty well.

Regards Kris

chiku
  • 485
  • 2
  • 8
  • 23
0

In my case, I wanted to update a field in Mongo DB and I had the JSON path for the field. I ended up using some simple string replace to do the conversion from JSON path to mongo query path.

private String toMongoPath(@Nonnull String jsonPath) {
    return jsonPath.replace("'", "")
            .replace("][", ".")
            .replace("$[", "")
            .replace("]", "");
}

Input:

$['store']['book'][0]['title']

Output:

store.book.0.title
Drunken Daddy
  • 7,326
  • 14
  • 70
  • 104