3

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

Samsul Hoque
  • 53
  • 1
  • 7
  • Does this answer your question? [How to create indexes in MongoDB via .NET](https://stackoverflow.com/questions/17807577/how-to-create-indexes-in-mongodb-via-net) – gunr2171 Aug 31 '21 at 15:42
  • @gunr2171 Thanks for responding. I have tried all those. But the text search is not working when I create indexes using the approaches mentioned in that article. It seems they are okay for usual document structure not on attributes inside the embedded documents. – Samsul Hoque Aug 31 '21 at 15:45
  • Can you [edit] your post with the code that doesn't work? It's best if you make a [mre]. – gunr2171 Aug 31 '21 at 15:46
  • @gunr2171 Sorry about that. I missed out that portion. I have edited the question and added code that didn't worked for me, – Samsul Hoque Aug 31 '21 at 15:58

0 Answers0