I want to create a connection to my database in MongoDB from Matlab R2015a. I have tried with both the drivers for C# and Java but none of them seem to work and I don't know what the problem is.
For Java:
Code:
javaaddpath('/%path%/mongodb-driver-3.0.0.jar')
import com.mongodb.*;
mongoClient = MongoClient();
db = mongoClient.getDB('myDB');
colls = db.getCollectionNames();
coll = db.getCollection('myCollection');
Error:
No appropriate method, property, or field 'getDB' for class 'MongoDB.Driver.MongoClient'.
For C#:
Code:
NET.addAssembly('%path%\CSharpDriver-2.0.0\MongoDB.Driver.dll');
import MongoDB.Driver.*;
mongoClient = MongoDB.Driver.MongoClient();
mongoServer = mongoClient.GetServer();
db = mongoClient.GetDatabase('myDB');
collection = db.GetCollection('myCollection');
Errors:
1. No appropriate method, property, or field 'GetServer' for class 'MongoDB.Driver.MongoClient'.
2. If I comment the GetServer line I get: No appropriate method, property, or field 'GetCollection' for class 'MongoDB.Driver.MongoDatabaseImpl'.
I don't know if I am missing something and it would be really helpful if I could make it work.
I have also tried with the driver for Matlab but I couldn't make it create the .dll.
Thanks.
You have to open the client with:
import com.mongodb.*;
mongoClient = MongoClient('myIP', 'myPort');
I'm using the java version with Matlab 2015b. I assume you have done the import correct. Otherwise, the MongoClient class would not be found.
Related
I am using Groovy to query on MongoDB and I am getting not authorized in querying in MongoDB. Can you please check if there is a problem on my script?
DBName default
Collection paymentHeader
import com.mongodb.*;
import com.mongodb.DB;
import com.mongodb.MongoCredential;
import org.apache.jmeter.protocol.mongodb.config.MongoDBHolder;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
//Get DB
DB db = MongoDBHolder.getDBFromSource("SITDB","${DBName}","${username}","${password}");
boolean auth = db.authenticate("${username}","${password}".toCharArray());
//Get Collection
DBCollection collection = db.getCollection("${Collection}");
//Find ApplicationNum
//collection.find({applicationNum: "${applicationId}"});
BasicDBObject query = new BasicDBObject("applicationNum", "${applicationId}");
DBObject result = collection.findOne(query);
SampleResult.setResponseData(result.toString().getBytes());
Response code: 500
Response message: javax.script.ScriptException: com.mongodb.MongoException: not authorized for query on default.paymentHeader
This doesn't have anything with JMeter, you need to provide read permissions for the ${username} onto default.paymentHeader collection.
Also be aware that you should not reference JMeter Functions or Variables as ${username}, you should use vars shorthand for JMeterVariables class instead like vars.get('username')
More information: JSR223 Sampler Documentation, in particular:
JMeter processes function and variable references before passing the script field to the interpreter, so the references will only be resolved once. Variable and function references in script files will be passed verbatim to the interpreter, which is likely to cause a syntax error. In order to use runtime variables, please use the appropriate props methods, e.g.
props.get("START.HMS");
props.put("PROP1","1234");
Could you please tell me how are you fetching specific details from the tracker store. Elaborating my doubt below:
in my run_app.py (socketIO class) i have used mongotracker like this-
db = MongoTrackerStore(domain=“d.yml”,host=‘host ip’, db=‘xyz’, username=“x”,password=“x”,collection=“x”,event_broker=None)
agent = Agent.load(‘models/dialogue’, interpreter=‘models/current/nlu’,action_endpoint = action_endpoint,tracker_store=db)
now i want to fetch some data like db.sender_id or db.event. the reason of doing it is to store it column wise on my mongodb.Please help me solving this problem.
This information should already be stored in your mongodb, so there should be no extra need for you to store it.
Maybe see the documentation for this https://rasa.com/docs/core/tracker_stores/ and make sure your endpoints.yml file includes the correct information:
tracker_store:
store_type: mongod
url: <url to your mongo instance, e.g. mongodb://localhost:27017>
db: <name of the db within your mongo instance, e.g. rasa>
username: <username used for authentication>
password: <password used for authentication>
auth_source: <database name associated with the user’s credentials>
For information on how to fetch specific details from your mongodb maybe have a look at the mongodb docs https://docs.mongodb.com/manual/reference/method/db.collection.find/.
look at this Example
I am using Pymongo to connect monogoDB. try to understand my code
from typing import Any, Text, Dict, List
from pymongo.database import Database
from pymongo import MongoClient
from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher
import pymongo
# url="http://localhost:3000/api"
client = pymongo.MongoClient("localhost", 27017)
db=client.sample
class mercdesCarAction(Action):
def name(self):
return "mercdesCarAction"
def run(self,dispatcher,tracker,domain):
res = db.datas.find({'action':'mercdesCarAction'})
for i in res:
dispatcher.utter_button_message(i['text'],i['buttons'])
return []
WebStorm gives me a warning of "Unrecognized function or method" on functions like:
Schema.find() [find() not recognized]
Schema.aggregate() [aggregate() not recognized]
Schema.findOneAndUpdate() [findOneAndUpdate() not recognized]
I've tried to Enabling the NodeJs core libraries and to install
mongodb-DefinitelyType
mongoose-DefinitelyType
mongoose-auto-increment-DefinitelyType
mongoose-deep-populate-DefinitelyType
mongoose-DefinitelyType
mongoose-mock-DefinitelyType
under Preferences > JavaScript > Libraries
But this has not solved my problem. Does someone knows a solution?
This issue is tracked as https://youtrack.jetbrains.com/issue/WEB-17099; please see https://youtrack.jetbrains.com/issue/WEB-17099#comment=27-1441265 for possible workaround
This is possible solution working for me without any issues.
Moving the relative path out of the require() statement as follows.
const PATH = '../models/';
const User = require(PATH + 'user');
Alternatively
Do not import Schema separately.
Just import mongoose like this
const mongoose = require('mongoose');
and use mongoose.Schema to access Schema
I don't know the reason but somehow this works:
export
module.exports.User = User; // your model
import
const User = require("../dbSchema/user.js").User;
Note that the schema is inserted correctly. Don't forget to check your Schema.
Sample
module.exports = mongoose.model('SampleCollection', SampleSchema);
I have a MongoDB connection string with the DB included. I am currently initializing the collection this way:
var mongoUrl = new MongoUrl(_connectionString);
var mongoClient = new MongoClient(mongoUrl);
var mongoServer = mongoClient.GetServer();
var mongoDatabase = mongoServer.GetDatabase(mongoUrl.DatabaseName);
_defaultCollection = mongoDatabase.GetCollection<Comment>("comments");
This works fine but just seems longer than it should be. Am I missing a less chatty way of doing the same thing?
Thanks
Matthew
Unfortunately you're not missing out on a thing - it's indeed a cumbersome way of achieving a common task.
I would encourage you to have a look at the excellent open source MongoRepository project which makes such simple tasks a breeze.
According to the pymongo documentation,
PyMongo is thread-safe and even provides built-in connection pooling for threaded applications.
I normally initiate my mongodb connection like this:
import pymongo
db = pymongo.Connection()['mydb']
and then I can just use it like db.users.find({'name':..})...
Does this mean that I can actually place that two lines in the lib/apps_global.py like:
class Globals(object):
def __init__(self, config):
self.cache = CacheManager(**parse_cache_config_options(config))
import pymongo
self.db_conn = pymongo.connection()
self.db = self.db_conn['simplesite']
and then in my base controller:
class BaseController(WSGIController):
def __call__(self, environ, start_response):
"""Invoke the Controller"""
# WSGIController.__call__ dispatches to the Controller method
# the request is routed to. This routing information is
# available in environ['pylons.routes_dict']
ret = WSGIController.__call__(self, environ, start_response)
# Don't forget to release the thread for mongodb
app_globals.db_conn.end_request()
return ret
And start calling app_global's db variable throughout my controllers?
I hope it is really that easy.
Ben Bangert, an author of Pylons, has written his blog engine with mongodb.
You can browse it's source code online.