受欢迎的博客标签

MongoDB stores data in JSON Documents. Actually, they are stored as Binary JSON (BSON) objects on disk

Data

{
    "_id": { "$oid":"56d5f7eb604eb380b0d8d8ce" },
    "student_id":{ "$numberDouble": "0" },
    "scores":[
        {"type":"exam","score": {"$numberDouble": "78.40446309504266" }},
        {"type":"quiz","score": {"$numberDouble": "73.36224783231339" }},
        {"type":"homework","score": {"$numberDouble": "46.980982486720535" }},
        {"type":"homework","score": {"$numberDouble": "76.67556138656222" }}
    ],
    "class_id":{"$numberDouble": "339"}
}

Connecting to a Specific Collection

using System;
using MongoDB.Bson;
using MongoDB.Driver;

namespace MongoDBCRUDExample {
    class Program {
        static void Main (string[] args) {
            MongoClient dbClient = new MongoClient ( << YOUR ATLAS CONNECTION STRING >>);

            var database = dbClient.GetDatabase ("sample_training");
            var collection = database.GetCollection<BsonDocument> ("grades");

        }
    }
}

1.Creating a BSON Document

var document = new BsonDocument { { "student_id", 10000 }, {
                "scores",
                new BsonArray {
                new BsonDocument { { "type", "exam" }, { "score", 88.12334193287023 } },
                new BsonDocument { { "type", "quiz" }, { "score", 74.92381029342834 } },
                new BsonDocument { { "type", "homework" }, { "score", 89.97929384290324 } },
                new BsonDocument { { "type", "homework" }, { "score", 82.12931030513218 } }
                }
                }, { "class_id", 480 }
        };

 await collection.InsertOneAsync (document);

2.Update a BSON Document

2.1 Update a single field

var filter = Builders<BsonDocument>.Filter.Eq("student_id", 10000)
var update = Builders<BsonDocument>.Update.Set("class_id", 483);
ollection.UpdateOne(filter, update);

2.2 Update Array

var arrayFilter = Builders<BsonDocument>.Filter.Eq("student_id", 10000) 
     & Builders<BsonDocument>.Filter.Eq("scores.type", "quiz");

var arrayUpdate = Builders<BsonDocument>.Update.Set("scores.$.score", 84.92381029342834);
collection.UpdateOne(arrayFilter , arrayUpdate);

3.Read document

var firstDocument = collection.Find(new BsonDocument()).FirstOrDefault();
Console.WriteLine(firstDocument.ToString());

output

{ "_id" : ObjectId("56d5f7eb604eb380b0d8d8ce"), 
"student_id" : 0.0, 
"scores" : [
{ "type" : "exam", "score" : 78.404463095042658 },
{ "type" : "quiz", "score" : 73.362247832313386 }, 
{ "type" : "homework", "score" : 46.980982486720535 }, 
{ "type" : "homework", "score" : 76.675561386562222 }
], 
"class_id" : 339.0 }

https://www.mongodb.com/blog/post/quick-start-c-and-mongodb--read-operations

4.delete document

//define the filter to match the student_id equal to 10000 document
var deleteFilter = Builders<BsonDocument>.Filter.Eq("student_id", 10000);
collection.DeleteOne(deleteFilter);

ElemMatch

//define a  filter to match the exam score being less than 60:
var deleteLowExamFilter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>("scores",
     new BsonDocument { { "type", "exam" }, {"score", new BsonDocument { { "$lt", 60 }}}
});

collection.DeleteMany(deleteLowExamFilter);

 

5.Query with multi filter

//step 1:Connect
var db = server.GetDatabase(bsDatabase.Current as string);
var collection = db.GetCollection(bsCollections.CurrencyManager.Current as string);
var allLevel = collection.Distinct("level");

//step 2:query 
//query 1
var query = Query.And(
                    Query.EQ("level", "ERROR"),
                    Query.Or(
                        Query.EQ("loggerName", "classa"),
                        Query.EQ("loggerName", "classb")
                    )
                );

//query 2
List<IMongoQuery> mainQueries = new List<IMongoQuery>();
if (!String.IsNullOrWhiteSpace(cmbLevel.Text))
{
    mainQueries.Add(Query.EQ("level", cmbLevel.Text));
}
if (cbList.CheckedIndices.Count > 0)
{
    List<IMongoQuery> listOfLoggerNameQueries = new List<IMongoQuery>();
 
    foreach (Int32 index in cbList.CheckedIndices)
    {
        String value = cbList.Items[index].ToString();
        listOfLoggerNameQueries.Add(Query.EQ("loggerName", value));
    }
    mainQueries.Add(Query.Or(listOfLoggerNameQueries.ToArray()));
}

//final query 
var finalQuery = Query.And(mainQueries.ToArray());


//search 
var cursor = collection.Find(finalQuery);
Int32 limit;
if (!Int32.TryParse(txtLogNum.Text, out limit))
{
    limit = 50;
}
cursor.SetFields("level", "loggerName", "message", "exception", "customproperties", "timestamp");
cursor.SetSortOrder(SortBy.Descending("timestamp"));
cursor.Limit = limit;

 

 var mongoString = "mongodb://jamesbing:[email protected]:27017";
 2             var host = new TMongodbHostModel
 3             {
 4                 CollectionName = "ft_test",
 5                 ConnectionString = mongoString,
 6                 DatabaseName = "system_db"
 7             };
 8 
 9             var person = new Person
10             {
11                 Id = ObjectId.GenerateNewId(),
12                 Name = "jamesbing",
13                 Address = new List<AddressItem>
14                 {
15                     new AddressItem {Add = "英国", Id = ObjectId.GenerateNewId(), Age = 12},
16                     new AddressItem {Add = "美国", Id = ObjectId.GenerateNewId(), Age = 19}
17                 }
18             };
19             //  var addresult = TMongodbHelper.Add(host, person);
20             var collection = TMongodbHelper.GetMongoCollection<Person>(host.ConnectionString, host.DatabaseName, host.CollectionName);
21 
22             //Update ChildDocument
23             var address = "Address.$";
24             var result = collection.Update(
25                 Query.And(new List<IMongoQuery>
26                 {
27                    Query.EQ("_id", new ObjectId("577b344a87aebb23c0fc767a")),
28                     Query.EQ("Address._id", new ObjectId("577b344a87aebb23c0fc767b")),
29                 }), Update.Set(address + ".Age", 33));
30 
31 
32             //Add ChildDocument
33             //单个
34             var result2 = collection.Update(Query.EQ("_id", new ObjectId("577b2d6787aebb198839d415")
35                ), Update.Push("Address", new AddressItem { Add = "山西省运城市", Id = ObjectId.GenerateNewId() }.ToBsonDocument()));
36 
37             //多个
38             var result3 = collection.Update(Query.EQ("_id", new ObjectId("577b262587aebb41fca9a3af")
39              ), Update.PushEach("Address", new[] { new AddressItem { Add = "山西省运城市4", Id = ObjectId.GenerateNewId(), Age = 10 }.ToBsonDocument(), new AddressItem { Add = "山西省运城市5", Id = ObjectId.GenerateNewId(), Age = 9 }.ToBsonDocument() }));
40 
41             //Remove ChildDocument
42             var result4 = collection.Update(Query.EQ("_id", new ObjectId("577b2d6787aebb198839d415")),
43                Update.Pull("Address", new { Id = new ObjectId("577b2d9387aebb2d7449367f") }.ToBsonDocument()));
44 
45 
46             //Query ChildDocument
47              var query = Query.EQ("_id", new ObjectId("577b30e087aebb34ec170e7a"));
                var q = Query.ElemMatch("Address"", Query.EQ("Add", "北京市"));     
                var result5= collection.FindOne(Query.And(query,q));  

https://www.cnblogs.com/gaobing/p/5667021.html

 

DateTime datetimestart =  new DateTime(2018, 5, 11, 14, 39, 33);
DateTime datetimeend =  new DateTime(2018, 5, 11, 14, 39, 40);
var filter1 = Builders<BsonDocument>.Filter.Eq("type", "ws128");
var filter2 = Builders<BsonDocument>.Filter.Gte("tsend", datetimeend);
var filter3 = Builders<BsonDocument>.Filter.Lt("tsend", datetimestart);

var andFilter = filter1 & filter2 & filter3;

var cursor = collection.Find(andFilter).ToCursor();

or
var cursor = collection.Find(filter1 & filter2 & filter3).ToCursor();

 

Projection

using System;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Core;

namespace Projections
{
  class Program
  {
    static void Main(string[] args)
    {
       callMain(args).Wait();
       Console.ReadLine();
    }
    static async Task callMain(string[] args)
    {
      var conString = "mongodb://localhost:27017";
      var Client = new MongoClient(conString);
      var DB = Client.GetDatabase("test");
      var collection = DB.GetCollection<BsonDocument>("store");
      var list = await collection.Find(new BsonDocument()).Project(Builders<BsonDocument>.Projection.Include("Price").Exclude("_id")).ToListAsync();
      foreach (var doc in list)
      {
          Console.WriteLine(doc);
      }
    }
  }
}