简体   繁体   中英

How can we create multiple indexes using CreateIndexModel in latest mongodb c# driver

I have to index 2 fields using CreateIndexModel , for single index I have tried this and its working.I am not sure how I can add one more field to index.

var indexModel = new CreateIndexModel<BsonDocument>(
                Builders<BsonDocument>.IndexKeys.Ascending(IndexField),
                new CreateIndexOptions
                {
                    Name = IndexName,
                    Background = true
                });
            collection.Indexes.CreateOne(indexModel);

if the goal is to create a compound index with multiple index keys, you can simply chain the builder methods like this:

Builders<Category>.IndexKeys
    .Ascending(x => x.Name)
    .Ascending(x => x.UserID);

just be aware that compound indexes have some limitations in mongo. just because you add all the fields of a query to an index doesn't mean they will all get used.

this blog post will give you more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM