在mongodb中使用Like运算符 [英] use of Like operator in mongodb

查看:119
本文介绍了在mongodb中使用Like运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在vb.net中进行开发

I am developing in vb.net

Dim dtDetails As DataTable = Utility.GetDetailsTable()
Dim resource_ids As new BsonArray

Dim dtrow = dtDetails.Select("id='" & user_id & "'")
If dtrow.Length > 0 Then
  For i As Integer = 0 To dtrow.Length - 1
   resource_ids.Add(".*" & Convert.ToString(dtrow(i)("instance_id")) & ".*")
  Next
End If

Dim queries = Query.And(
    Query.EQ("user_id", user_id),
    Query.Matches("resource_id", resource_ids )
)

Dim Docs = ceilometer.GetCollection("meter").Find(queries)

文档返回为空.我需要使用类似于sql的类似运算符发送多个resource_id,例如%abc%"这样的resource_ids或%def%"这样的resource_ids.

Docs returns as empty. I need to send multiple resource_ids with like operator similar to sql is resource_ids like "%abc%" or resource_ids like "%def%".

请帮助.

推荐答案

您可以尝试使用MongoRegex进行此类查询(请参见 如何使用MongoRegex-MongoDB C#驱动程序 以获取更多信息).例如,在MongoDB Shell中,您可以在正则表达式内使用"|"来匹配多个替代项,例如:

You could try using MongoRegex for this kind of query (see MongoDB - Advanced Queries - Regular Expressions and How to use MongoRegex - MongoDB C# Driver for more info). As an example in MongoDB shell, you can use "|" inside a regular expression to match multiple alternatives, like this:

db.collection.find({"resource_id": /abc|def|ghi|jkl/i})

正则表达式将针对resource_id中的所有条目进行测试,只需要匹配一个条目,文档就将包含在结果中.请记住,MongoDB每个查询只能使用一个索引,而使用正则表达式的查询仅在正则表达式已生根且区分大小写时才使用索引.因此,您的最终代码应如下所示:

The regular expression will be tested against all the entries in resource_id and all it takes is for one entry to match and the document will be included in the results. Do keep this in mind that MongoDB can only use one index per query and queries that use regular expressions only use an index when the regex is rooted and case sensitive. So your final code should look like:

Dim searchKey As String = ""

Dim dtrow = dtDetails.Select("id='" & user_id & "'")
If dtrow.Length > 0 Then
    For i As Integer = 0 To dtrow.Length - 1
       If i > 0 Then
          searchKey += "|"
       End If
       searchKey += Convert.ToString(dtrow(i)("instance_id"))
    Next
End If

Dim queries = Query.And(
    Query.EQ("user_id", user_id),
    Query.Matches("resource_id", new Regex(searchKey, i))
)

Dim Docs = ceilometer.GetCollection("meter").Find(queries)

这篇关于在mongodb中使用Like运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆