更新多级嵌入式mongo数组

时间:2012-06-20 13:15:59

标签: c# mongodb

我无法找到正确的语法来替换嵌套在集合深处几层的对象数组。我的偏好是只更新单个属性,但是自从阅读下面的链接后,似乎更换整个数组是最好的选择。

https://jira.mongodb.org/browse/SERVER-831

所以我将以下类作为例子:

public class Parent
    {
        public ObjectId _id { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public Collection<Child> Children { get; set; }
    }

    public class Child
    {
        public ObjectId _id { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public Collection<Pet> Pets { get; set; }
    }

    public class Pet
    {
        public string Name { get; set; }
    }

使用以下代码我创建一个Parent,添加一些Children,并向其中一个子项添加Pet。

// Construct Objects
Parent parent = new Parent() { _id = new ObjectId("4f979621682dbc1a8cefecb1") };

Collection<Child> children = new Collection<Child>();
Collection<Pet> pets = new Collection<Pet>();

children.Add(new Child() 
    { _id = new ObjectId("4f979621682dbc1a8cefecaf"), 
      Firstname = "Child", 
      Lastname = "One" });
children.Add(new Child() 
    { _id = new ObjectId("4f979621682dbc1a8cefecb0"), 
      Firstname = "Child", 
      Lastname = "Two" });
pets.Add(new Pet() { Name = "Fishy" });

parent.Children = children;
parent.Children[0].Pets = pets;

// Connect to Mongo
var server = MongoServer.Create("mongodb://localhost/?safe=true");
var db = server.GetDatabase("test");

// Insert into parent collection
MongoCollection<Parent> parents;
parents = db.GetCollection<Parent>("parents");
parents.Insert<Parent>(parent, MongoDB.Driver.SafeMode.True);

这成功插入了对象,生成以下JSON结果:

{   "_id" : ObjectId("4f979621682dbc1a8cefecb1"),
    "Firstname" : null,
    "Lastname" : null,
    "Children" : 
    [
        {
            "_id" : ObjectId("4f979621682dbc1a8cefecaf"),
            "Firstname" : "Child",
            "Lastname" : "One",
            "Pets" : 
            [
                {
                    "Name" : "Fishy"
                }
            ]
        },
        {
            "_id" : ObjectId("4f979621682dbc1a8cefecb0"),
            "Firstname" : "Child",
            "Lastname" : "Two",
            "Pets" : null
        }
    ]
}

更新单个文档元素似乎也是一个简单的过程,并且可以使用以下代码成功运行。

// Change children's name
var query = new QueryDocument { { "Children._id", new ObjectId("4f979621682dbc1a8cefecaf") } };
var update = Update.Set("Children.$.Firstname", "Something");
parents.Update(query, update);

现在我无法解决的问题是如何更换Pets数组。以下代码无法编译为Update.Set不接受Collection。

// Change pets information
pets[0].Name = "Fishy2"; // change to pet
pets.Add(new Pet() { Name = "Doggy" }); // add new pet

query = new QueryDocument { { "Children._id", new ObjectId("4f979621682dbc1a8cefecaf") } };
update = Update.Set("Children.$.Pets", pets);
parents.Update(query, update);

那么什么是让我更新Pets数组中的详细信息的最佳流程?

2 个答案:

答案 0 :(得分:2)

以下是您要查找的代码:您需要将BsonArray传递给Update.Set值。要创建该数组,您需要将每个“pets”包装在BsonDocumentWrapper中,以便序列化库知道如何正确地序列化它们。

var query = new QueryDocument { { "Children._id", new ObjectId("4f979621682dbc1a8cefecaf") } };
var petDocuments = BsonDocumentWrapper.CreateMultiple(pets);
var petArray = new BsonArray(petDocuments);
var update = Update.Set("Children.$.Pets", petArray);
parents.Update(query, update);

答案 1 :(得分:0)

> db.Questions.find().pretty()
{
        "Answers" : [
                {
                        "_id" : ObjectId("52ae4946e1df9e1b10e1f6e1"),
                        "Text" : "ans",
                        "Comments" : [ ]
                }
        ],
        "CreatedDate" : ISODate("2013-12-16T00:28:47.790Z"),
        "QuestionText" : "test",
        "QuestionTitle" : "test",
        "Tag" : "test",
        "UserID" : "singleuserid_777",
        "_id" : ObjectId("52ae493fe1df9e1b10e1f6e0")
}
>

现在,如果我需要更新Questions集合中Answers数组中的Comments数组,那么我的C#.Net代码将

  base.GetContext.Collection.Find(Query.EQ("Answers._id", ObjectId.Parse(Id))).Collection.Update(Query.EQ("Answers._id", ObjectId.Parse(Id)),MongoDB.Driver.Builders.Update.PushWrapped("Answers.$.Comments", comm));