MongoDB C# CRUD (3)

题记:媳妇要求发上来。这篇我要上首页。

1,NuGet引入MongoDB。接着是命名空间

using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Driver.Linq;

 2,全局声明

 
MongoDatabase mongo = new MongoClient(ConfigurationManager.AppSettings["PSConnStrMongoDB"]).GetServer().GetDatabase("psNew");
MongoCollection arts = null;

 3,实例化

arts = mongo.GetCollection<ArticleForMongo>("artNew");

 4,组织List,批插。过瘾的批插

List<ArticleForMongo> artIns = ai.Select(e => new ArticleForMongo
{
	IntArticleID = Convert.ToInt32(e.IntArticleID),
	...
        IntFree = Convert.ToInt32(e.IntFree)

}).ToList();

//批插
arts.InsertBatch(typeof(ArticleForMongo), artIns);

 

5,组织ID List,批删

foreach (ArticleList ali in ad)
 {
     sd.Append(ali.IntArticleID + ",");
 }
 DeleteArticle(sd.ToString().TrimEnd(‘,‘));

    批删

List<IMongoQuery> listQuery = new List<IMongoQuery>();
string[] aidList = aid.Split(‘,‘); 
foreach (string id in aidList)
{
      listQuery.Add(Query.EQ("_id", Convert.ToInt32(id))); 
}
IMongoQuery query = Query.Or(listQuery);
WriteConcernResult result = arts.Remove(query);
bool bl = result != null && result.Ok;

 6,改

            	public bool UpdateArticle(ArticleForMongo arm)
		{
			IMongoQuery query;
			query = Query.And(Query.EQ("_id", arm.IntArticleID));
			BsonDocument bsonDocument = arm.ToBsonDocument<ArticleForMongo>();
			bsonDocument.Remove("_id");

			var update = new UpdateDocument { { "$set", bsonDocument } };
			WriteConcernResult result = arts.Update(query, update);

			bool bl = result != null && result.Ok;

			//if (bl)
			//{
			//	Common.AppendTxtFile(opearFilePath, "修改成功 ID:" + arm.IntArticleID);
			//}
			if (!bl)
			{
				Common.AppendTxtFile(opearFilePath, "修改失败 ID:" + arm.IntArticleID);
			}
			return bl;
		}

 7,查

 8,索引

 9,性能优化

....

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。