簡體   English   中英

阻止mongoDB中的更改字段

[英]Block a change field in mongoDB

我在MongoDB中有一個集合,它增加了,該字段最初被定義為一個整數,但我發現在增加之后轉換為double。

但后來我對文檔進行了更新,看到對Long的更改。

有沒有辦法阻止Mongo中的這些變化?

提前致謝

MongoDB是無架構的。 Schamalessness可以更輕松地更改數據結構,但代價是數據庫不強制執行類型約束等操作。 您需要在應用程序代碼中遵守規則,以確保按照您希望的方式保留事物。

如果您需要確保數據始終是Integer類型,那么建議您的應用程序通過應用程序中的數據訪問層訪問MongoDB。 數據訪問層可以強制執行類型約束(以及您希望放在對象上的任何其他約束)。

簡短回答:沒有辦法在MongoDB中強制執行此操作。

由於MongoDB每個集合沒有固定的模式,因此無法在數據庫端阻止此類更改。 確保您在任何地方使用相同的數據類型,包括其更新操作。 C#驅動程序非常聰明。

使用外殼時要小心,它可能會有刺激性。 默認情況下,mongo shell會將每個數字視為double ,例如:

> db.Inc.find().pretty();
{ "_id" : 1, "Number" : 1000023272226647000 }
// this number is waaayyy larger than the largest 32 bit int, but there's no
// NumberLong here. So it must be double.
> db.Inc.update({}, {$inc: {"Number" : 1 }});
> db.Inc.find().pretty();
{ "_id" : 1, "Number" : 1000023272226647000 }
// Yikes, the $inc doesn't work anymore because of precision loss

我們來使用NumberLong

> db.Inc.insert({"Number" : NumberLong("1000023272226647000")});
> db.Inc.update({}, {$inc: {"Number" : 1}});
> db.Inc.find();
{ "Number" : 1000023272226647000, "_id" : 1 }
// Yikes! type conversion changed to double again! Also note 
// that the _id field moved to the end

讓我們在$inc使用NumberLong

> db.Inc.insert({"Number" : NumberLong("1000023272226647000")});
> db.Inc.update({}, {$inc: {"Number" : NumberLong("1")}});
> db.Inc.find();
{ "_id" : 1, "Number" : NumberLong("1000023272226647001") }
// This actually worked

在C#中,以下兩個更新都有效, Number仍然很長:

class Counter { public long Number {get;set;} public ObjectId Id {get;set;} }
var collection = db.GetCollection("Counter");
collection.Insert(new Counter { Number = 1234 }); 
collection.Update(Query.Null, Update<Counter>.Inc(p => p.Number, 1)); // works
collection.Update(Query.Null, Update.Inc("Number", 1)); // works too

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM