实体定义:



[BsonIgnoreExtraElements]
public class Person : BaseEntity
{
public string FirstName { get; set; }

public string LastName { get; set; }

public string Password { get; set; }

public List<Attr> Attribute { get; set; }
}


public class Attr
{
public string Id { get; set; }

public string Name { get; set; }
}


 

数据库存储内容形式:



{
"_id" : ObjectId("5af189270d8ef62bb49d045e"),
"FirstName" : "1",
"LastName" : "2",
"Password" : "3",
"Attribute" : [
{
"_id" : "4",
"Name" : "4"
},
{
"_id" : "5",
"Name" : "5"
},
{
"_id" : "6",
"Name" : "6"
}
]
}


MongoDB内嵌文档操作_技术

 

 

1. 删除内嵌字段的值:


 如删除Attribute子集合:



var filter = Builders<Person>.Filter.Where(x => x.Id == id);
var update = Builders<Person>.Update.Unset(x => x.Attribute);
var result = this.personRepository.Collection.UpdateOne(filter, update);


 

2. 删除Attribute集合中Id等于6的内嵌文档



var filter = Builders<Person>.Filter.Where(x => x.Id == id);
var update = Builders<Person>.Update.PullFilter<Attr>(x => x.Attribute, y => y.Id.Equals("6"));
var result = this.personRepository.Collection.UpdateOne(filter, update);


 或者



var filter = Builders<Person>.Filter.Where(x => x.Id == id);
var update = Builders<Person>.Update.PullFilter(x => x.Attribute, y => y.Id.Equals("6"));
var result = this.personRepository.Collection.UpdateOne(filter, update);


或者

var filter = Builders<Person>.Filter.Where(x => x.Id == id);

var update = Builders<Person>.Update.PullFilter("Attribute", Builders<Attr>.Filter.Eq("_id",6));

var result = this.personRepository.Collection.UpdateOne(filter, update);

 

3. 更新FirstName的值



var filter = Builders<Person>.Filter.Where(x => x.Id == id);
var update = Builders<Person>.Update.Set(x => x.FirstName, "22222");
var result = this.personRepository.Collection.UpdateOne(filter, update);


4. 往Attribute里添加一条记录



var filter = Builders<Person>.Filter.Where(x => x.Id == id);
var update = Builders<Person>.Update.Push<Attr>(x => x.Attribute, new Attr() { Id = "7", Name = "7" });
var result = this.personRepository.Collection.UpdateOne(filter, update);