Using MongoDB shell commands on MongoDB 10Gen'

2019-06-22 17:03发布

问题:

I want to simply execute pure MongoDB queries via MongoDb 10Gen's .net(c#) driver.

For example . I want to use below command on driver

db.people.update( { name:"Joe" }, { $inc: { n : 1 } } );

I am not sure how can i do this. I am not interested in how to do via high level api classes.

回答1:

The C# driver (or any other driver) is not intended to "directly" run mongo shell commands. That's what the shell is for. What you need to do is translate the mongo shell commands into the equivalent C# statements.

If you want to run mongo shell commands then run them in the mongo shell.



回答2:

You can construct queries i c# using the fluent Query interface. Those query can then be fired towards the databse using the Find method on a Mongo collection. E.g:

var myDatabase = MongoDatabase.Create(connectionString);
var myCollection = database.GetCollection<MyType>("myCollectionNameInDB");
var myCollection = 
var myQuery = Query.EQ("name", "joe");
var someDataFromDB =  myCollection.Find(myQuery).FirstOrDefault();

Query can also be used with updates. E.g.:

myCollection.Update(
                   myQuery,
                   Update.Replace(new MyType(){...}),
                   UpdateFlags.Upsert
              );

This just replaced the whole document. For finegrained control you can use the Update API combined with the FindAndModify method. E.g:

var myUpdate = Update.Inc("n", 1);
var result = myCollection.FindAndModify(
                   myQuery,
                   SortBy.Descending("name");
                   myUpdate,
                   true // return new document
             );

Check out http://www.mongodb.org/display/DOCS/CSharp+Driver+Tutorial for more information.