如何在 C# 代码中使用 MongoDB 的 Postional Operator? [英] How to use MongoDB's Postional Operator in C# code?
问题描述
我想在 C# 代码中使用 MongoDB 的位置运算符.这是客户的数据结构:
I want to use the positional operator of the MongoDB in C# code. Here is data structure for Customer:
{
name:"Robert",
age:40,
addresses:[
{street:"...", city:"New York", country:"USA", ...},
{street:"...", city:"California", country:"USA", ...},
],
}
因此,如果我想更新纽约市地址所在的街道值,我会在 MongoDB 中使用此查询:
So, if I want to update the street value where the address if of New York city, I use this query in MongoDB:
db.customer.update(
{ "addresses.city" : "New York"},
{ $set : {
"addresses.$" : {"street":"New street", city:"New York", country:"USA",...}
} }, false, true);
在 C# 代码中使用的等效查询是什么?如何在 C# 代码中使用位置运算符?
What is the equivalent query to use in C# code? How to use the positional operator in C# code?
我正在使用官方的 MongoDB 驱动程序.
I'm using the official MongoDB driver.
推荐答案
你会在 C# 中这样写:
You would write that in C# like this:
var newAddress = new BsonDocument
{
{ "street", "New street" },
{ "city", "New York" },
{ "country", "USA" }
// ...
};
var query = Query.EQ("addresses.city", "New York");
var update = Update.Set("addresses.$", newAddress);
var result = customerCollection.Update(query, update, UpdateFlags.Multi);
这似乎是一个危险的更新;您仅根据城市匹配覆盖街道地址?查询在 mongo shell 中是否正常工作?
That does seem like a dangerous update to make; you're overwriting a street address based only on the city matching? Is the query working correctly in the mongo shell?
这篇关于如何在 C# 代码中使用 MongoDB 的 Postional Operator?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!