[英]How to filter documents in a collection if any of their properties has 'x' word? (MongoDB driver, C#)
Let's say I have documents in a collection called "alerts" with the following structure:假设我在名为“警报”的集合中有文档,其结构如下:
{
"_id": {
"$oid": "5f299ed8905bcf0001cd9a56"
},
"CreatedDate": {
"$date": "2020-08-04T17:46:00.862Z"
},
"Name": "Alert name",
"Description": "Alert description",
"AlertTypeId": {
"$oid": "5f299ea7905bcf0001cd9a54"
}
"AlertTrigger": {
"Variation": "moreThan",
"Amount": 5
},
"Emails": ["hello@hotmail.com", "test@gmail.com"]
}
In my .Net app I have the class representation as:在我的 .Net 应用程序中,我的类表示为:
[BsonCollection("alerts")]
public class Alert
{
public ObjectId Id { get; set; }
public DateTime CreatedDate { get; set; }
public string Name { get; set; }
public string Description { get; set; }
[BsonRepresentation(BsonType.ObjectId)]
public string AlertTypeId { get; set; }
public AlertTrigger AlertTrigger { get; set; }
public ICollection<string> Emails { get; set; }
}
public class AlertTrigger
{
public string Variation { get; set; }
public double Amount { get; set; }
}
What I would like to do is to filter documents that contain certain "keyword" in any of their properties.我想要做的是过滤在其任何属性中包含某些“关键字”的文档。 For example, if I filter by the word "moreThan" or the word "hello", the element above would be found, because they are contained in its properties.例如,如果我按单词“moreThan”或单词“hello”进行过滤,则会找到上面的元素,因为它们包含在其属性中。
How can I achieve this using MongoDB Driver, LinQ, C# ?如何使用 MongoDB Driver、LinQ、C# 实现这一点?
The C# Linq abstraction does not contain a way to do this. C# Linq 抽象不包含执行此操作的方法。 However, in MongoDB, you'll be able to create a text index on all the fields in your collection.但是,在 MongoDB 中,您将能够在集合中的所有字段上创建文本索引。
db.collection.createIndex( { "$**": "text" } )
Then you'll be able to do a text search on your collection in C# by writing the following.然后,您将能够通过编写以下内容在 C# 中对您的集合进行文本搜索。
var client = new MongoClient();
var db = client.GetDatabase("text");
var collection = db.GetCollection<Alert>("alerts");
var filter = Builders<Alert>.Filter.Text("moreThan");
var result = await collection.Find(filter).ToListAsync();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.