我有这样的结构:
public class User
{
public ObjectId Id { get; set; }
public Location Location { get; set; }
public DateTime LastAround {get;set;}
}
public class Location
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
我已经尝试了一些方法,但我想更新用户的位置以及他们上次出现的时间。
尝试过这个:
userHelper.Collection.Update(
Query.EQ("_id", userId),
Update.SetWrapped<Location>("Location", new Location { Latitude = latitude, Longitude = longitude }).Set("LastAround", DateTime.UtcNow));
还有这个:
userHelper.Collection.Update(
Query.EQ("_id", userId),
Update.Set("Location.Latitude", latitude)
.Set("Location.Longitude", longitude)
.Set("LastAround", DateTime.UtcNow));
没有任何作用...我该怎么做?
4/17 更新:
userHelper.Collection.Update(
Query.EQ("_id", new ObjectId(userId)),
Update
.SetWrapped<Location>("Location", new Location { Longitude = longitude, Latitude = latitude })
.Set("LastAround", DateTime.UtcNow)
);
在对 lng 和 lat 值进行查询时,它们似乎非常重要。我正在做一个 geonear 查询并得到一个奇怪的越界错误。如果您以错误的顺序更新,它将把纬度放在第一位,然后您会收到错误。
最佳答案
您的两个原始 Update 语句都应该有效。我编写了一个小示例程序来演示。
执行此插入语句后:
var userId = ObjectId.GenerateNewId();
var user = new User
{
Id = userId,
Location = new Location { Latitude = 1.0, Longitude = 2.0 },
LastAround = new DateTime(2012, 4, 14, 0, 0, 0, DateTimeKind.Utc)
};
collection.Insert(user);
该文档在 mongo shell 中如下所示:
> db.test.find()
{ "_id" : ObjectId("4f8c5d33e447ad34b8c7ac84"), "Location" : { "Latitude" : 1, "Longitude" : 2 }, "LastAround" : ISODate("2012-04-14T00:00:00Z") }
>
执行第一种形式的Update语句后:
collection.Update(
Query.EQ("_id", userId),
Update
.SetWrapped<Location>("Location", new Location { Latitude = 3.0, Longitude = 4.0 })
.Set("LastAround", new DateTime(2012, 4, 15, 0, 0, 0, DateTimeKind.Utc)));
文档如下所示:
> db.test.find()
{ "_id" : ObjectId("4f8c5d33e447ad34b8c7ac84"), "Location" : { "Latitude" : 3, "Longitude" : 4 }, "LastAround" : ISODate("2012-04-15T00:00:00Z") }
>
执行第二种形式的Update语句后:
collection.Update(
Query.EQ("_id", userId),
Update
.Set("Location.Latitude", 5.0)
.Set("Location.Longitude", 6.0)
.Set("LastAround", new DateTime(2012, 4, 16, 0, 0, 0, DateTimeKind.Utc)));
文档如下所示:
> db.test.find()
{ "_id" : ObjectId("4f8c5d33e447ad34b8c7ac84"), "Location" : { "Latitude" : 5, "Longitude" : 6 }, "LastAround" : ISODate("2012-04-16T00:00:00Z") }
>
因此,两种形式的 Update 语句都有效。
完整的程序在这里:
关于mongodb - 如何使用 10gen C# 驱动程序更新内部属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10158764/