在MongoDB中匹配数组到字符串

本文关键字:数组 字符串 MongoDB | 更新日期: 2023-09-27 18:03:52

我试图通过匹配字符串数组到mongoDB文档中的特定字符串对象来获得mongoDB的搜索结果。My Sample MongoDb Document.

"Notedisp" : {
   "NoteID" : NumberLong(100281),
   "NoteTitle" : null,
   "NoteContent" : "In mathematics, the Pythagorean theorem theorem, also known as Pythagoras's theorem, is a relation in Euclidean geometry among the three sides of a right triangle. It states that the square of the hypotenuse (the side opposite the right angle) is equal to the sum of the squares of the other two sides. The theorem can be written as an equation relating the lengths of the sides a, b and c, often called the '"Pythagorean equation'"'r'n'r'na^2 + b^2 = c^2 ,'r'nwhere c represents the length of the hypotenuse and a and b the lengths of the triangle's other two sides.",       
 },

我已经尝试了以下代码。

var listTearm = ["what","is","Pythagorean","theorem"]
var filter = (builder.AnyIn("Notedisp.NoteContent", listTearm)

在上面的代码"Notedisp。"noteconent"是MongoDB文档中的字符串对象,它返回空字符串。所以有任何特定的方式,我可以匹配字符串到MogoDb文档,它可以返回特定的数据。

在MongoDB中匹配数组到字符串

对于一个简化的对象,

public class Note
{
  [BsonId] public long Id { get; set; }
  [BsonElement("content")] public string Content { get; set; }
}

首先你必须在你的集合上创建一个文本索引:

  IndexKeysDefinition<Note> keys = "{ content: '"text'" }";
  string contentTextSearchIndex = await _collection.Indexes.CreateOneAsync(keys);

然后用$text运算符匹配任何搜索项:

var fdb = Builders<Note>.Filter;
var cursor = await _collection.FindAsync(fdb.Text("what is Pythagorean theorem"));
var docs = await cursor.ToListAsync();