更新MongoDB集合中的条目

时间:2014-06-18 19:05:50

标签: c# mongodb

我无法想象如何更新MongoDB集合中的条目。我看过C#驱动程序docs,我想我已经非常密切地关注它了。

但是,我传递给Update方法的一个(或两个?)参数无效。谁能告诉我我做错了什么?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using MongoDB.Driver.Linq;


namespace Csharp_Linq
{
    class Program
    {
        public class Book
        {
            // Fields
            public string title { get; set; }
            public string author { get; set; }
            public ObjectId id { get; set; }

            // Constructors
            public Book()
            {
                this.title = "some title";
                this.author = "some author";
            }

            public Book(string title, string author)
            {
                this.title = title;
                this.author = author;
            }

        }

        static void Main(string[] args)
        {
            // Connect to the server
            string connectionString = "mongodb://localhost";
            MongoClient client = new MongoClient(connectionString);
            MongoServer server = client.GetServer();

            // Get the database then the collection
            MongoDatabase database = server.GetDatabase("tutorial");
            MongoCollection collection = database.GetCollection("books");

            // Query the collection
            int count =
                (from book in collection.AsQueryable<Book>()
                 select book)
                .Count();

            string numBooks = String.Format("This collection has {0} books.", count);
            Console.WriteLine(numBooks);

            var query =
                from book in collection.AsQueryable<Book>()
                where book.author == "Ernest Hemingway"
                select book;

            foreach (var book in query)
            {
                string bookInfo = String.Format("{0} by {1}", book.title, book.author);
                Console.WriteLine(bookInfo);
            }

            // Insert new books
            Book scaryBook = new Book("Dr. Sleep", "Stephen King");
            Book[] batch = 
            {
                new Book(),
                scaryBook
            };
            collection.InsertBatch(batch);

            // Update default book
            var query2 =
                from book in collection.AsQueryable<Book>()
                where book.title == "some title" && book.author == "some author"
                select book;

            var update = new UpdateDocument {
                { "$set", new BsonDocument("title", "War and Peace") }
            };
            BsonDocument updatedBook = collection.Update(query2, update);

            Console.ReadLine();
        }
    }
}

我有点惊讶的是,Update方法实际上返回了一个BsonDocument。为什么这样做?

之前我尝试使用Update对象,如示例所示:

MongoCollection<BsonDocument> books;
var query = Query.And(
    Query.EQ("author", "Kurt Vonnegut"),
    Query.EQ("title", "Cats Craddle")
);
var update = Update.Set("title", "Cat's Cradle");
BsonDocument updatedBook = books.Update(query, update);

此对象是否仍然存在?每当我在Visual Studio中输入它时,我都会收到错误消息,说明该对象不在命名空间中。

3 个答案:

答案 0 :(得分:2)

首先我必须包括

using MongoDB.Driver.Builders;

然后我不得不将我的Linq查询转换为Mongo查询。以下是生成的代码:

        // Update default book
        var query2 =
            from book in collection.AsQueryable<Book>()
            where book.title == "some title" && book.author == "some author"
            select book;
        // Cast linq query to Mongo query
        var mongoQuery = ((MongoQueryable<Book>)query2).GetMongoQuery();

        var update = new UpdateDocument {
            { "$set", new BsonDocument("title", "War and Peace") }
        };
        collection.Update(mongoQuery, update);

进行了一些研究,以使所有的部分适合!

答案 1 :(得分:0)

Update对象是MongoDB.Driver.Builders命名空间的一部分,尽管这在本教程中并不明显。

认为问题与您的查询有关。除非你有一本书

 book.title == "some title" && book.author == "some author"

您无法找到任何要更新的内容。

如果您将其添加到代码文件中,那么第二个示例将起作用(一次)。

using MongoDB.Driver.Builders;

答案 2 :(得分:0)

您可以通过以下方式更新条目。以项目添加到购物车为例

db.carts.update({
_id: "the_users_session_id", status:'active'
}, {
 $set: { modified_on: ISODate() },
 $push: {
   products: {
     sku: "111445GB3", quantity: 1, title: "Simsong One mobile phone", price:1000
   }
 }
});

请参阅以下内容以获取更多信息http://advancedmongodb.blogspot.in/