MongoDB Embedded Document Operations

Entity Definition:

    [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; }
    }

 

The form of database storage content:

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

 

 

1. Delete the value of the embedded field:

 For example, delete the Attribute embedded field:

 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. Delete the embedded document with Id equal to 6 in the Attribute collection

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);

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325853358&siteId=291194637