[英]MongoDB, C#, Linq, Query, Update on a generic List item
我是MongoVerse的新手,但我的問題如下:
var connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
var server = client.GetServer();
var database = server.GetDatabase("test");
var collection = database.GetCollection<Entity>("entities");
var entity = new Entity { Name = "Tom" };
collection.Insert(entity);
var id = entity.guid;
var query = Query<Entity>.EQ(e => e.guid, id);
var entity2 = collection.FindOne(query);
Console.WriteLine("Getting entity2 works!");
for (int i = 0; i < 100; i++)
{
var ourPoint = ((MongoQueryable<List<SubEntity<object>>>)(from q in collection.AsQueryable<Entity>() where q.guid == id select q.thePackage)).GetMongoQuery();
var ourUpdate = Update<List<SubEntity<object>>>.Set(q => q[i], new SubEntity<object>() { value = 3.14 });
collection.Update(ourPoint, ourUpdate);
}
var entity3 = collection.FindOne(query);
Console.WriteLine("Getting entity3 throws an error!");
System.IO.FileFormatException:元素“ 0”與類名稱空間+ Entity的任何字段或屬性都不匹配
我正在序列化的類如下:
public class Entity
{
[BsonId]
public ObjectId guid = new ObjectId();
public string Name = "";
public List<SubEntity<object>> thePackage = new List<SubEntity<object>>();
public Entity()
{
for (int i = 0 ; i < 100; i++)
{
thePackage.Add(new SubEntity<object>() { value = Math.PI });
}
}
}
子類是:
public class SubEntity<T>
{
public DateTime dateTime = DateTime.Now;
public T value = default(T);
}
我懷疑Linq查詢不受支持,或者沒有正確進行。 我從文檔中看到的是Select查詢是在客戶端執行的,但是使用StopWatches,執行操作所需的時間似乎正確了(與覆蓋整個List <>相比)。
我在流行的方案Data Analysis Schema(在Mongo的站點上)上讀了一些東西,似乎涉及到創建一個文檔,該文檔的數組中包含空白條目(小時,天,周,具體取決於您使用數字的頻率) ),然后一次寫入一個值。
我對Linq問題感到好奇嗎? 有人知道我的下一站將是什么嗎? 但是,我真的只是想獲得一個很好的示例,說明如何從數組中一次更新1個值。 (在我可能不知道數據類型或數組大小的地方)
我將繼續尋找(它的atm太晚了,所以我的搜索可能會推遲),如果找到答案,我會回發我的答案。
我正在使用Windows 8的MongoDB 2.6標准版(64位Windows和mongo)。 我還復制了Windows 7計算機上的錯誤。
我沒有找到答案,但是我改變了方法。 (10/9/2014)
我自己使用BsonDocument類進行了序列化。 寫時間從60ms減少到不到1ms。 替換列表中的一項大約需要6毫秒。 我仍然不確定如何替換任意BsonArray元素,但是它的速度足夠快,不再是一個問題。
不支持此行:
Update<List<SubEntity<object>>>.Set(q => q[i], new SubEntity<object>() { value = 3.14 });
我們在第一個參數中需要一個元素名稱,而q [i]不是一個。 但是,這看起來像是我們應該修復的錯誤。 隨時在CSHARP項目下的jira.mongodb.org上提交Jira票證。
現在,您需要使用無類型查詢構建器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.