Query a stored procedure in mongodb using spring boot - mongodb

I want to query a stored procedure in mongodb. I can query it using the command line tool but facing issue while querying using java.The piece of code(last two lines) that is throwing error is :
MongoClient mongoClient = new MongoClient();
MongoDatabase mdb = mongoClient.getDatabase("mydb");
mdb.runCommand(new Document("$eval", "db.loadServerScripts()"));
Document doc1 = mdb.runCommand(new Document("$eval", "mysp(5)"));
and the error that it's throwing is 'no such command: '$eval'' on server localhost:27017. The full response is {"ok": 0.0, "errmsg": "no such command: '$eval'", "code": 59, "codeName": "CommandNotFound"}
Now I read several posts and documentation as well stating that $eval or db.eval() doesn't works for mongo version 4.2. So what should I change in my code to make it work or what should be the possible solution. I know this question has been asked several times but those solutions are obsolete , so I need help for this. Can anyone help.

From mongodb-4.2, the support for the eval command is deprecated now.
So I guess the only option will be to use mongodb-4.0 as of now.
Source : https://docs.mongodb.com/manual/reference/method/db.eval/

Related

Error cloning collection using Cosmic Clone

I'm trying to clone an existing MongoDB collection that is running on azure cosmos DB to another collection on the same DB using Cosmic Clone.
access validation succeeds but the process fails with the following error message:
Collection Copy log
Begin Document Migration.
Source Database: myDB Source Collection: X
Target Database: myDB Target Collection: Y
LogError
Error: Error reading JObject from JsonReader. Path '', line 0, position 0., Message: Error reading JObject from JsonReader. Path '', line 0, position 0.
Main process exits with error
LogError
Error: One or more errors occurred., Message: Error reading JObject from JsonReader. Path '', line 0, position 0.
Any ideas are appreciated.
I've not used this tool but I took a quick look at the source for it and I'm fairly certain it is not designed to work with MongoDB collections in Cosmos DB.
If you're looking to copy a MongoDB collection you're better off using native Mongo tools like mongodump and mongorestore.
More details here, https://docs.mongodb.com/database-tools/

pymongo - MongoClient retryWrites=false is not working

I'm currently working on a simple python CRUD script to check MongoDB out. Turns out I'm liking it a lot, but I have found myself being unable to work with MongoDB transactions. Everytime I try to start a transaction an exception is thrown saying:
This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.
And, eventhough I've already added that option to my connection string:
self._client = MongoClient('mongodb://localhost/?retryWrites=false')
self._db = self._client.workouts
self._collection = self._db.workouts
That error is still popping up when running the following lines of code:
with self._client.start_session() as s:
with s.start_transaction():
self._collection.delete_one({'_id': id}, session=s)
next = self._collection.find_one({'_id': next_id}, session=s)
return next
What can I do?
I'm running python 3.7.3, pymongo 3.9.0 and MongoDB 4.0.12.

MongoDB "no SNI name sent" error from heroku java application

I followed this tutorial to deploy a sample application to Heroku. I just added the below method in MyResource class and returned the result from it instead of "Hello World" from getIt() method. I'm connecting to an atlas free tier cluster:
static String getMessage() {
MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://<USER>:<PASSWORD>#cluster0-shard-00-00-2lbue.mongodb.net:27017,cluster0-shard-00-01-2lbue.mongodb.net:27017,cluster0-shard-00-02-2lbue.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin"));
DB database = mongoClient.getDB("mastery");
DBCollection collection = database.getCollection("summary");
DBObject query = new BasicDBObject("_id", new ObjectId("5c563fa2645d6b444c018dcb"));
DBCursor cursor = collection.find(query);
return (String)cursor.one().get("message");
}
This is the driver I'm using:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.9.1</version>
</dependency>
This is my import:
import com.mongodb.*;
The application works fine from my local system. But I face the below error when I deploy the application to Heroku and hit the service:
INFO: Exception in monitor thread while connecting to server cluster0-shard-00-01-2lbue.mongodb.net:27017
com.mongodb.MongoCommandException: Command failed with error 8000 (AtlasError): 'no SNI name sent, make sure using a MongoDB 3.4+ driver/shell.' on server cluster0-shard-00-01-2lbue.mongodb.net:27017. The full response is { "ok" : 0, "errmsg" : "no SNI name sent, make sure using a MongoDB 3.4+ driver/shell.", "code" : 8000, "codeName" : "AtlasError" }
at com.mongodb.internal.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:179)
at com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:299)
at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:255)
at com.mongodb.internal.connection.CommandHelper.sendAndReceive(CommandHelper.java:83)
at com.mongodb.internal.connection.CommandHelper.executeCommand(CommandHelper.java:33)
at com.mongodb.internal.connection.InternalStreamConnectionInitializer.initializeConnectionDescription(InternalStreamConnectionInitializer.java:106)
at com.mongodb.internal.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:63)
at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:127)
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:117)
at java.lang.Thread.run(Thread.java:748)
What is this SNI name? I can understand that the drivers are able to pick it from my machine, but not from Heroku machine. But I'm clueless on how to go about solving this! Is there a way to configure Heroku to reveal the SNI name when the driver asks for it? Can we get this value manually from somewhere in Heroku and directly feed it to the MongoDB drivers? Any help is appreciated.
EDIT:
It turned out that the client mentions the SNI name of the server it wishes to connect to as part of TLS security. And there seems to be a way to manually indicate the name in python driver. Is there any way to do this from java? Still puzzled why this is not an issue when running the app locally.
The code I was using to connect to the cluster turned out to be wrong. I followed the directions from the docs and it mentioned this:
To connect to an Atlas M0 (Free Tier) cluster, you must use Java
version 8 or greater and use a Java driver version that supports
MongoDB 3.4.
So I changed the java version to 1.8 in system.properties file:
java.runtime.version=1.8
It was earlier set to 1.7. I was also getting a deprecation warning on one of the methods I had used. So I again followed the docs to use the latest code and it worked like a charm.
The real takeaway here is to refer to the official docs everytime :)

Type error on mongodb 3

When i try to insert data on mongodb 3 through command line it's showing following error
use video;
switched to db video
db.movies.insertOne({ "title": "Jaws", "year": 1975, "imdb": "tt0073195" });
2018-03-26T12:42:42.233+0530 E QUERY TypeError: Property 'insertOne' of object video.movies is not a function at (shell):1:11`
but video db also not created
Please help me to rectify this problem.
MongoDB supports db.collection.insertOne() from version 3.2, please check your mongodb version by using the mongo shell command
db.version()
References:
insertOne
version
Try with db.movies.insert instead of db.movies.insertOne and check If it's working fine. If it's working then your mongo version is less than 3.2. If not then share your mongoDb console Screenshot.

Aggregation not working with monger for mongodb version 3.6

Mongo aggregation framework has some changes in version 3.6 Earlier aggregation queries with monger are not working even when we pass :cursor {} as an option. Is there any workaround or do we have to wait for the next monger release?. The error we get is specified below
MongoCommandException Command failed with error 9: 'The 'cursor' option is required, except for aggregate with the explain argument' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "The 'cursor' option is required, except for aggregate with the explain argument", "code" : 9, "codeName" : "FailedToParse" } com.mongodb.connection.ProtocolHelper.getCommandFailureException (ProtocolHelper.java:115)
by OSt advice, I could run monger aggregation sample with codes below.
(mc/aggregate db coll
[{"$project" {:subtotal {"$multiply" ["$quantity", "$price"]}
:_id "$state"}}]
:cursor {:batch-size 0})
thanks!
According to mongo db spec, cursor became a required field in some cases. So you should provide it through monger API. It is not a problem in monger, it is a breakable change in mongo db API.