Hi, @Jorn_Kersseboom,
Welcome to the MongoDB Community Forums.
I understand that the MongoDB .NET/C# Driver is not returning the same results as MongoDB Compass for a $text
search. I inserted the following 3 documents in a collection via mongosh
:
[
{
_id: ObjectId("64076217e3c19f9160c2fd0e"),
words: 'word1 word2 word3'
},
{
_id: ObjectId("6407621ce3c19f9160c2fd0f"),
words: 'word1 word2 word3 word4'
},
{
_id: ObjectId("64076226e3c19f9160c2fd10"),
words: 'wordr2 word1 word3'
}
]
and created a text
index:
db.textsearch.createIndex({words: "text"})
Running the text search in mongosh
the first two documents are returned, but not the third (as expected):
test> db.textsearch.aggregate([{ $match: { $text: { $search: "\"word1 word2 word3\"" } } }])
[
{
_id: ObjectId("64076217e3c19f9160c2fd0e"),
words: 'word1 word2 word3'
},
{
_id: ObjectId("6407621ce3c19f9160c2fd0f"),
words: 'word1 word2 word3 word4'
}
]
Running the following minimal C# repro:
using System;
using MongoDB.Bson;
using MongoDB.Driver;
var client = new MongoClient();
var db = client.GetDatabase("test");
var coll = db.GetCollection<BsonDocument>("textsearch");
var searchRequest = new { Query = "word1 word2 word3" };
var stage1 = new BsonDocument("$match", new BsonDocument("$text",
new BsonDocument("$search", $"\"{searchRequest.Query}\""
)));
var query = coll.Aggregate().AppendStage<BsonDocument>(stage1);
foreach (var doc in query.ToList())
{
Console.WriteLine(doc);
}
Console.WriteLine(query);
I received back the same two documents. I also print out the MQL that is sent to the server, which is the same as executed in mongosh
:
{ "_id" : ObjectId("64076217e3c19f9160c2fd0e"), "words" : "word1 word2 word3" }
{ "_id" : ObjectId("6407621ce3c19f9160c2fd0f"), "words" : "word1 word2 word3 word4" }
aggregate([{ "$match" : { "$text" : { "$search" : "\"word1 word2 word3\"" } } }])
I would recommend writing your aggregation pipeline to the console to look for any differences potentially added by other stages.
NOTE: You can use Builders<T>.Filter.Text
to construct the query stage rather than BsonDocument
.
var filter = Builders<BsonDocument>.Filter.Text($"\"{searchRequest.Query}\"");
var query = coll.Aggregate().Match(filter);
Console.WriteLine(query);
This outputs the identical query as displayed above.
Hope that helps in your debugging efforts.
Sincerely,
James