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

4
  • Does this answer your question? How to create indexes in MongoDB via .NET Commented Aug 31, 2021 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. Commented Aug 31, 2021 at 15:45
  • Can you edit your post with the code that doesn't work? It's best if you make a minimal reproducible example. Commented Aug 31, 2021 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, Commented Aug 31, 2021 at 15:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.