如何创建和读取索引Mongodb C#

时间:2017-04-24 16:20:34

标签: c# mongodb

我正在使用.Net驱动程序版本2.4,而且我无法找到确保集合索引的方法。我能够通过shell

来做到这一点
db.getCollection("myCollection").ensureIndex({"Location.Coordinates":"2dsphere"});

我见过有人在做

collection.EnsureIndex(keys, options)

我无法使用当前的驱动程序版本找到该方法。

更新 我发现以下代码可用于创建索引

 var index = Builders<myType>.IndexKeys.Geo2DSphere("Location.Coordinates");
 collection.Indexes.CreateOne(index);

现在我想确定一个索引是否存在。我有这个查询返回索引作为BsonDocument但在反序列化BsonDocument时遇到问题。 它返回shell中的以下对象

 [
       {
            "v" : 2,
            "key" : {
                "_id" : 1
            },
            "name" : "_id_",
            "ns" : "mydb.myCollection"
       }
    ]

我正在使用以下类反序列化此对象

internal class MongoDbIndex
    {
        public int v { get; set; }

        public string name { get; set; }

        public string ns { get; set; }

        public Dictionary<object,object> key { get; set; }

    }

在密钥属性上存在问题,因为不同的索引具有不同的数据类型。

1 个答案:

答案 0 :(得分:3)

最后,我可以通过以下方式确保地理位置指数

var index = Builders<MyCollection>.IndexKeys.Geo2DSphere("Location.Coordinates");
db.MyCollection.Indexes.CreateOne(index);

通过执行此操作,它将首次创建索引,其余时间如果已存在则不会创建重复索引。

最新版本的mongodb C#Driver中没有

EnsureIndex方法。