Search using search index in c#

How can I create a search query in c# to match exact word that I specify. For eg lets say my dataset is in the following way:

{_id: 1, "name": "Hello World"}
{_id: 2, "name": "Hello"}
{_id: 3, "name": "Tree and grass"}
{_id: 4, "name": "Cat and Dog"}
{_id: 5, "name": "and"}
var filter = Builders<MyClass>.Search.Text(x => x.Name, new List<string> { "Hello", "and" });
var result = _collection.Aggregate().Search(filter, indexName: "WordIdx").ToList();

The result here will contain all the elements that is

{_id: 1, "name": "Hello World"}
{_id: 2, "name": "Hello"}
{_id: 3, "name": "Tree and grass"}
{_id: 4, "name": "Cat and Dog"}
{_id: 5, "name": "and"}

But I only want {_id: 2, “name”: “Hello”} and {_id: 5, “name”: “and”}.
Should I use _collection.Aggregate().Search(filter, indexName: “WordIdx”).Limit(2).ToList()? But I am worried about my results being inaccurate

Hi @Akshay_Katoch and welcome to MongoDB community forums!!

If I understand your question correctly, you are trying to extract the documents from the collection which has names and either as “hello” or “and”.

While Atlas Search gives you the benefit of faster query execution, this feature is helpful if you wish to get the documents from the collection with text that contain the specific words in between.

I tried to replicate the sample documents given as above and use the Atlas Search and Text Search
Using Atlas Search:
Search Index:

{
  "mappings": {
    "dynamic": true,
    "fields": {
      "name": {
        "type": "string"
      }
    }
  }
}

Search Query:

[
  {
    $search: {
      index: "serachIndex",
      text: {
        query: "and, hello",
        path: "name"
      }
    }
  }
]

As you you have mentioned correctly, this gives all the documents in the collection and adding a $limit operator would certainly have the chance of returning unexpected results (especially if your dataset is much larger).

On the other hand, since it seems you are after the exact matches, you can create the following index db.collection.createIndex({"name":"text"}) which would support the below query that returns the documents you are after:

{
  "name": {
    $in: ["and", "Hello"]
  }
}

The equivalent c# code would look like the following:

using MongoDB.Bson;
using MongoDB.Driver;

new BsonDocument("name", new BsonDocument("$in", new BsonArray
        {
            "and",
            "Hello"
        }))

Please let me know if I have been mistaken in understanding your concern.

Warm Regards
Aasawari