欢迎光临

木子屋

标题: C#操作MongoDB简单示例

作者: dnawo

日期: 2012-08-09 04:28 PM

分类: Win编程

内容: 复制内容到剪贴板 程序代码using System;
using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Driver.Linq;
namespace ConsoleApplication2
{
public class User
{
public ObjectId Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
var connectionString = "mongodb://localhost/?safe=true";
var server = MongoServer.Create(connectionString);
var database = server.GetDatabase("test");
var collection = database.GetCollection<User>("user");

//增加
collection.Insert(new User() { Name = "user1", Age = 20 });
collection.Insert(new User() { Name = "user2", Age = 25 });
collection.Insert(new User() { Name = "user3", Age = 30 });
//修改
var user = collection.AsQueryable().FirstOrDefault(s => s.Name == "user1");
if (user != null)
{
user.Age = 28;
collection.Save(user);
}
//删除
var query = Query.EQ("Name", "user2");
collection.Remove(query);

//查询记录
var result = from item in collection.AsQueryable()
where item.Age >= 25
select item;
foreach (var item in result)
Console.WriteLine("{0},{1}", item.Name, item.Age);

Console.ReadKey();
database.DropCollection("user");
}
}
}
本例使用MongoDB版本：2.0.6

+ 查看当前日志评论 (0)

登录

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 1.479 ms

返回

标题: C#操作MongoDB简单示例

你没有权限发表评论

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 1.479 ms

返回

暂无评论

返回

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 1.510 ms

返回