使用Mongo C#2.0驱动程序替换嵌入式文档

时间:2016-10-19 21:15:32

标签: c# mongodb nosql

我有一个包含嵌入式单元数组的文档,如下所示:

{
    "_id" : ObjectId("5807c22e959ca231f0c48a75"),
    "Code" : "Value",
    "Units" : [ 
        {
            "_id" : ObjectId("5807cc08959ca331f09c530e"),
            "Code" : "Foo",
            "Label" : "Foo"
        },
        {
            "_id" : ObjectId("5807cc08959ca331f09c530e"),
            "Code" : "Bar",
            "Label" : "Bar"
        },
    ]
}

我希望通过其ID找到一个单位,并将其替换为新文档。 我怎么能使用Mongo C#Driver 2.0?

提前致谢!

2 个答案:

答案 0 :(得分:4)

谢谢你们。根据您的回答,我提出了以下解决方案:

var mainDocumentId = "5807c22e959ca231f0c48a75";
var arrayItemId = "5807cc08959ca331f09c530e"; //Id for foo

var unit = new Unit(...)
var filter = Builders<UnitType>.Eq(o => o.Id, mainDocumentId); // optional
filter &= Builders<UnitType>.Filter.ElemMatch(o => o.Units, o => o.Id == arrayItemId);
var update = Builders<UnitType>.Update.Set(o => o.Units[-1], unit);

collection.UpdateOne(filter, update);

答案 1 :(得分:3)

假设您在C#中的模型如下所示:

public class UnitLog
{
    [BsonRepresentation(BsonType.ObjectId)]
    [BsonId]
    public string Id { get; set; }

    public string Code { get; set; }

    public List<Unit> Units { get; set; }
}

public class Unit
{
    [BsonRepresentation(BsonType.ObjectId)]
    [BsonId]
    public string Id { get; set; }

    public string Code { get; set; }

    public string Label { get; set; }
}

您可以使用PullFilter从嵌入式阵列中拉取项目。以下是MongoDb 2.0驱动程序的示例:

var mainDocumentId = "5807c22e959ca231f0c48a75";//Your containing document's Id
var arrayItemId = "5807cc08959ca331f09c530e";//Id for array item with Code=foo

var pullFilter = Builders<UnitLog>.Update.PullFilter(
        x => x.Units,
        x => x.Id == arrayItemId 
    );

//Note that you would use Collection.UpdateManyAsync()  
//if you expected more than one item to be updated/pulled
var result = await Collection.UpdateOneAsync(
        x => x.Id == mainDocumentId,
        pullFilter
    ).ConfigureAwait(false);

要识别嵌入数组中的项目,您可以使用$ elemMatch作为此

ElemMatch MongoDb documentation

可以找到ElemMatch

Builders<UnitLog>.Filter.ElemMatch 

可与$ set结合使用,以更新使用$ elemMatch识别的嵌入文档的各个属性。

查看AddToSet,您可能会发现这很有用,因为它会向项目添加项目,除非该项目已存在

AddToSet MongoDb documentation

可以找到AddToSet

Builders<UnitLog>.Update.AddToSet