How to run mongodb shell query from c# using mongodb driver - javascript

I want to run below mongo query from C#. Currently I am using mongodb C# driver 2.7
db.changelog.find({}).forEach(function(doc){
//make javascript object dynimacally
var newDoc = {
"key": "value",
"doc": doc
}
db.changelog_log.insertOne(newDoc); })
This is successfully run into mongo shell, now I want to execute that script from c# application with modify object value dynamically. I was hoping it would be able to parse those queries and pass them off to database.RunCommand but I have not been able to make any progress.
var bsonDoc = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>("query");
database.RunCommand(command);
That code fails on the call to Deserialize with this error message: [Additional information: JSON reader was expecting a value but found 'db'.] which makes perfect sense because the script is not valid JSON.
After mongo 3.0 eval function has been depreciated.
So I'm having trouble parsing the script into something that can be executed.

VehicleModel is a model which I am using for inserting and same for retrieving,
so it replaces with your model
var collection = database.GetCollection<VehicleModel>("VehicleModel");
var Data = await collection.Find(Builders<VehicleModel>.Filter.Empty).ToListAsync();
foreach(VehicleModel vm in Data)
{
var newDoc =
{
"key": "value",
"doc": vm
collection.InsertOneAsync(value);
}
}
Maybe you are looking for this

Related

Get StdOut from RunCommand using Azure VM Javascript SDK

I'm using the Azure VM Javascript SDK in my Node.js webApp. I'm trying to use the RunCommand Function to run a custom script on my Azure virtual machines.
The problem I'm having is with obtaining the response from running the command which should contain the StdOut and StdErr strings.
If I run the command from the Azure CLI, Like the following:
az vm run-command invoke -g 'myResource' -n 'myVm' --command-id RunPowerShellScript --scripts 'Get-ChildItem -Name'
Then I am able to receive the response, e.g. (notice in the 'message' section there is a listing of the files returned from 'Get-ChildItem')
{
"value": [
{
"code": "ComponentStatus/StdOut/succeeded",
"displayStatus": "Provisioning succeeded",
"level": "Info",
"message": "myTxtFile.txt\nscript12.ps1\nscript13.ps1\nscript14.ps1\nscript15.ps1\nscript16.ps1\nscript17.ps1\nscript18.ps1\nscript19.ps1\nscript20.ps1\nscript21.ps1\nscript22.ps1\nscript23.ps1\nscript24.ps1\nscript25.ps1\nscript26.ps1",
"time": null
},
{
"code": "ComponentStatus/StdErr/succeeded",
"displayStatus": "Provisioning succeeded",
"level": "Info",
"message": "",
"time": null
}
]
}
However, when I run this code from the javascript SDK I don't get any thing returned. Here is the code:
let usr = ...;
let pas = ...;
let subscriptionId = ...;
let client = null;
msRestAzure.loginWithUsernamePassword(usr, pas, function(err, credentials) {
if (err) return console.log(err);
client = new azureArmCompute.ComputeManagementClient(credentials, subscriptionId);
let param = {
commandId: 'RunPowerShellScript',
script: [
'echo $null >> myTxtFile.txt\n' +
'Get-ChildItem -Name\n'
]
};
client.virtualMachines.runCommand('myResource', 'myVm', param, function (err, result) {
console.log(err);
console.log(result);
})
});
and here is what is printed to the console:
null
{}
I know that the script is actually running because I tried, and was successfully able, to create a text file (myTxtFile.txt).
Anyone have any clues as to why I'm not getting anything in the result object?
Edit 1 (in response to #Itay):
Looking at the source, the callback is supposed to be a "ServiceCallback" of type "RunCommandResult". Here are the three function declarations for RunCommand.
Here's the declaration for the ServiceCallback interface.
So in my callback I was expecting there to be four returns "err" and "result" and "request" and "response" (I'm obviously leaving off the latter two). In my example I'm printing the error and result objects to the console, but the result object doesn't have anything in it...
I think the signature for the callback you defined is not as described by the documentation.
Looking at runCommand(string, string, RunCommandInput, ServiceCallback< RunCommandResult >), it seems that the callback should be accepting a RunCommandResult interface, which in turn, contains a property called Value which is an array of InstanceViewStatus interface instances that might hold the information you are looking for.
Hope it helps!

Express with JSON Data Control

I use lowDB dependency to control the JSON Data with Express and actually it works. But there is a bug and I cannot find how to solve it.
I create /create page to add information in JSON file and it contains 4 form and submit button.
And In express I code like this. each forms data will save it in variable and push with lowdb module.
router.post('/post', function (req, res) {
let pjName = req.body.projectName;
let pjURL = req.body.projectURL;
let pjtExplanation = req.body.projectExplanation;
let pjImgURL = req.body.projectImgURL;
console.log(pjName);
db.get('project').push({
name: pjName,
url: pjURL,
explanation: pjtExplanation,
imgurl: pjImgURL
}).write();
console.log(db.get('project'));
console.log(db.get('project').value());
res.redirect('/');
})
And it works well. But when I modify the JSON file myself (ex. reset the JSON file) and execute again. It shows the data that I reset before. I think in this app somewhere saves the all data and show save it in array again.
And When I shutdown the app in CMD and execute again, the Array is initialized.
As you may already know the lowdb persist the data into your secondary memory (hdd), and may return a promise depending on your environment when you call write method.As mentioned in the doc
Persists database using adapter.write (depending on the adapter, may return a promise).
So the data may be still getting write when you read them, so the old data is queried. Try this,
db.get('project').push({
name: pjName,
url: pjURL,
explanation: pjtExplanation,
imgurl: pjImgURL
}).write().then(() => {
console.log(db.get('project'));
console.log(db.get('project').value());
});

can not get data with MysqlSubscription of numtel:mysql for meteor

I am using meteor to do full stack javascript work.And I want to use mysql instead of mongodb.I find numtel:mysql on github, which is a Reactive MySQL for Meteor.
On the server side
Meteor.publish('test', function(){
let array = liveDb.select(
'select * from tasks',
[ { table: 'tasks' } ]
);
console.log('publish test mysql')
console.log(array);
return array;
});
on the client side
let mysqlData = new MysqlSubscription('test');
console.log('subscribe mysql data at client');
console.log(mysqlData);
console.log(mysqlData.length);
console.log(mysqlData.subscriptionId);
console.log(mysqlData[0]);
console.log(mysqlData[1]);
However, I can not get data on the client.And there is a strange phenomenon.From the logs, I find data of mysqlData.However, mysqlData.length is 0, mysqlData[0] and mysqlData[1] are undefined.
Who can help me?
You might want to call mysqlData.reactive() and check if it is ready by using mysqlData.ready() first.
In case the subscription does not work (it does not update the data automatically), you should make sure that you config your MySQL server correctly following the installation instruction.
For me, I could not make it work when I used capital letter on the database name, you should check it also.

Run javascript file from MongoDB C# driver

I'm trying to use Variety, a custom tool/script for MongoDB (2.6) in the C# driver for MongoDB.
I was able to run it successfully through the commandline, but I'm unsure how to run it's equivalent in the C# driver.
bin\mongo db --eval "var collection = 'coll', limit = 20" bin\variety.js
1. Javascript location
I ran the command above when the javascript was located in bin\ next to mongo.exe. Following the manual I went on and placed the file in \data\db\scripts. However I also read about the system.js file.
Is placing it in \data\db\scripts the right way? Or do I have to register it in system.js?
2. Running the script
This example on running a stored procedure in MongoDB shows how to execute a method with two arguments. However the Variety tool uses some sort of context variables which I need to provide in order for it to execute (collection and limit for instance). In the commandline they are provided as string which is evaluated before the name of the script file.
What is the equivalent of the commandline execution? I can't get the result2 variable right. How do I pass an entire script file instead of a function name?
MongoClient client = new MongoClient("mongodb://0.0.0.0/db");
MongoServer server = client.GetServer();
MongoDatabase db = server.GetDatabase("db");
BsonValue result1 = db.Eval("var collection = 'coll', limit = 20");
BsonValue result2 = db.Eval(result1.AsBsonJavaScript.Code, "variety.js");

Finding saved data from mongo shell (no output)

Here is the code for initialization
mongoose.connect('mongodb://localhost/gpsdb');
var db = mongoose.connection;
db.on('open', function () {
// now we can start talking
});
After successful opening, I am saving data like this, it's giving me no errors.
function saveGPSData(data){
var newData = new GPSData(data);
newData.save(function(err){
if(err)
return console.error(err);
});
}
Now in mongo shell, I am trying to retrieve that data but it's giving me empty output.
> use gpsdb
> db.GPSData.find();
>
It's giving me no output. Also can I found what models are there in gpsdb?
Here is the full source code http://pastebin.com/K7QPYAx8
JUST FOUND THAT in db folder there these files for my db created by mongodb
/data/db/gpsdb.0
/data/db/gpsdb.1
/data/db/gpsdb.n
A good place to start to get a quick answer is
https://groups.google.com/forum/#!forum/mongoose-orm
the community is very responsive :)
In the shell I did the following
>use gpsdb
switched to gpsdb
>db show collections
gpsdatas
From here I found that collection name is gpsdatas...... Not sure why its adding extra (s) to my modal, although you can see from the code that I am setting Modal to
var GPSData = mongoose.model('GPSData', GPSDataSchema);
Now using the shell its working like this
>db.gpsdatas.find()

Categories