【问题标题】:Mongodb 2dsphere disallow empty geometryMongodb 2dsphere 不允许空几何
【发布时间】:2019-03-14 21:32:40
【问题描述】:

mongodb中的2dsphere几何索引有严格模式吗?

mongodb 可以防止存储 empty 几何(空列表,空字典)吗?

测试用例:

$ mongo
MongoDB shell version v4.0.6
...
> use geotest
switched to db geotest
> db.places.createIndex({'geometry': '2dsphere'})
{
        "createdCollectionAutomatically" : true,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}

...到目前为止一切顺利。

> db.places.insert({'geometry': [[]]})  // this fails -> good
WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 16755,
                "errmsg" : "Can't extract geo keys: { _id: ObjectId('5c8a483bcebc3f30972cb9ea'), geometry: [ [] ] }  Point must only contain numeric elements"
        }
})

...很高兴这失败了,但是:

> db.places.insert({'geometry': []})    // can I make mongo fail here too?
WriteResult({ "nInserted" : 1 })
> db.places.insert({'geometry': {}})    // and here?
WriteResult({ "nInserted" : 1 })
> db.places.insert({'geometry': null})  // how about this one?
WriteResult({ "nInserted" : 1 })
> db.places.find()
{ "_id" : ObjectId("5c8a4840cebc3f30972cb9eb"), "geometry" : [ ] }
{ "_id" : ObjectId("5c8a4843cebc3f30972cb9ec"), "geometry" : {  } }
{ "_id" : ObjectId("5c8a4b23cebc3f30972cb9ee"), "geometry" : null }

...不会失败。我能以某种方式让它失败吗?

【问题讨论】:

标签: mongodb mongodb-query


【解决方案1】:

感谢@alex-blex 的提示!

对新集合使用验证器:

> db.createCollection("places", {validator: {"geometry.type": {$in:
... ["Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon"]
... }}})
{ "ok" : 1 }
> db.places.createIndex({'geometry': '2dsphere'})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}

现在我们无法插入空几何:

> db.places.insert({'geometry': []})
WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 121,
                "errmsg" : "Document failed validation"
        }
})
> db.places.insert({'geometry': {}})
WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 121,
                "errmsg" : "Document failed validation"
        }
})
> db.places.insert({'geometry': null})
WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 121,
                "errmsg" : "Document failed validation"
        }
})

将验证器添加到现有集合:

> db.places.createIndex({'geometry': '2dsphere'})
{
        "createdCollectionAutomatically" : true,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
> db.runCommand({ collMod: 'places', validator: {"geometry.type": {$in:
... ["Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon"]
... }}})
{ "ok" : 1 }

【讨论】:

    猜你喜欢
    • 2014-07-18
    • 1970-01-01
    • 2014-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    • 2020-05-12
    相关资源
    最近更新 更多