C#中使用1.7版本驱动操作MongoDB简单例子

2019-12-26 11:21:44王旭

考虑下面的类定义:

复制代码
public class Entity
{
    public ObjectId Id { get; set; }

 

    public string Name { get; set; }
}


对一组对象的引用

 

你会得到一个包含引用集合 实体 文件是这样的:

复制代码
// "entities" is the name of the collection
var collection = database.GetCollection<Entity>("entities");
插入文档

 

插入一个 实体 :

复制代码
var entity = new Entity { Name = "Tom" };
collection.Insert(entity);
var id = entity.Id; // Insert will set the Id if necessary (as it was in this example)
找到一个现有的文档

 

在这个示例中,我们将读回 实体 假设我们知道 ID 值:

复制代码
var query = Query<Entity>.EQ(e => e.Id, id);
var entity = collection.FindOne(query);
查询<单位> .EQ 使用 查询< T > 构建器类来构建 查询。 lambda表达式 E = > e.Id 是翻译 _ID 。 这是 字段的名称存储在数据库中。