Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create mongo view using pymongo?

I am looking for a way to create a MongoDB 3.4+ view using pymongo from the following pipeline:

db.getCollection('parsed_tests').aggregate([{
  $lookup: {
    from: "raw_tests",
    localField: "repository_path",
    foreignField: "repository_path",
    as: "raw_data"
  }
}])

I want to do it in Python to have an initialization script in one piece. Has anyone managed to do this?

like image 337
niedakh Avatar asked Sep 07 '25 20:09

niedakh


2 Answers

As sstyvane says, you'll need to give an explicit database command. Unfortunately, they got the syntax wrong.

This worked for me:

db.command('create', 'parsed_and_raw_tests', viewOn='parsed_tests', pipeline=my_pipeline)

Also, if you've got a Mongo instance that upgraded from version 3.2 or earlier, you'll need to set the feature compatibility version to 3.4 before you can create a view.

like image 69
Neil Smith Avatar answered Sep 10 '25 13:09

Neil Smith


PyMongo does not provide a Database method to create a view. However you can run the create command to create your view with the command method. If fact createView is just a wrapper around the create command.

db.command({
    "create": "parsed_tests_view",
    "viewOn": "parsed_tests", 
    "pipeline": pipeline
})
like image 40
styvane Avatar answered Sep 10 '25 13:09

styvane