I have following document in my MongoDB database:
{
"_id":1,
"user_name":"John Doe",
"addresses":[
{
"_id":null,
"geolocation":null,
"city":"Toronto"
},
{
"_id":null,
"geolocation":null,
"city":"Canada"
}
]
}
I want to create an index for the attribute addresses.city
in my C# code so that I can do a text based search later. How can I achieve this?
By the way, I have implemented the following code to achieve this but it seems it doesn't work while running the query:
public void createIndexes() {
try {
var indexOptions = new CreateIndexOptions();
var indexKeys = Builders < Users> .IndexKeys.Text(_ => _.Addresses);
var indexModel = new CreateIndexModel < Users> (indexKeys, indexOptions);
var collection = _mongoDb.GetCollection < Users> ("users");
collection.Indexes.CreateOneAsync(indexModel);
} catch (Exception ex) {
throw;
}
}
The code executing the query:
//Creates connection with the mongodb
private MongoDbContext db = new MongoDbContext();
...
...
//Initializes the search term
string searchTerm = "Cana";
//Executes the query
var builder = Builders<Users>.Filter;
FilterDefinition<Users> filter;
filter = builder.Text(searchTerm);
var results = await db.Users.Find(filter).ToListAsync();
I'm using this MongoDB driver