匹配mongodb中字段中的任何单词或部分单词

时间:2022-09-13 09:19:42

I am using MongoDB and the Mongoid ODM for MongoDB in Rails. I have a field called name and one of the document name value is " John Paul Zeni". So for example:

我在Rails中使用MongoDB和Mongoid ODM for MongoDB。我有一个名为name的字段,其中一个文档名称值为“John Paul Zeni”。例如:

{ "_id" : ObjectId("582bab8f9f26631b8a000088"), "name" : " JOHN PAUL ZENI", "email" : "", "fax" : "", ...

{“_ id”:ObjectId(“582bab8f9f26631b8a000088”),“name”:“JOHN PAUL ZENI”,“email”:“”,“fax”:“”,...

I want to find this document with the keyword "John Zeni". Now if I search with " JOHN PAUL ZENI", it works:

我想找到关键字“John Zeni”的这个文件。现在,如果我搜索“JOHN PAUL ZENI”,它的作用是:

Contact.where(name: " John Paul Zeni").first
# => #<Contact _id: 582fab8d9f26631605000054, created_at: 2016-11-19 01:31:57 UTC, ...

But if I search by first and last name, it does not yield results:

但是,如果我按名字和姓氏搜索,它不会产生结果:

 Contact.where(name: "John Zeni").first
# => nil 

It should produce the result even if I search by first name and just a portion of the last name, like so:

即使我使用名字和姓氏的一部分进行搜索,它也应该产生结果,如下所示:

Contact.where(name: "John Zen").first

Currently, I am using the following search:

目前,我正在使用以下搜索:

Contact.where({name: /.*#{condition}.*/i })

And it is not doing what I want, as I described above. How can I search a field by first name and last name or first name and part of last name or part of first name or first name and middle name? (I accept a solution either in MongoDB or Mongoid. I do not necessarily need a Mongoid solution. I can convert MongoDB solution into Mongoid.)

而且正如我上面所描述的那样,它并没有按照我的意愿行事。如何通过名字和姓氏或名字以及姓氏的一部分或名字或名字和中间名的一部分来搜索字段? (我接受MongoDB或Mongoid中的解决方案。我不一定需要Mongoid解决方案。我可以将MongoDB解决方案转换为Mongoid。)

2 个解决方案

#1


1  

Not a great solution but it works:

不是一个很好的解决方案但它有效:

condition = "John Smith"
regex = '^(?=.*' + condition.split(/\s+/).map{ |x| Regexp.quote(x) }.join(')(?=.*') + ')'
@contacts = Contact.where({name: /#{regex}/i })

#2


0  

You can use $regex from monogDB.

您可以使用monogDB中的$ regex。

Collection.where(name: {'$regex': params[:search], '$options': 'i'})

it will return all the data similar to name string.

它将返回类似于name string的所有数据。

#1


1  

Not a great solution but it works:

不是一个很好的解决方案但它有效:

condition = "John Smith"
regex = '^(?=.*' + condition.split(/\s+/).map{ |x| Regexp.quote(x) }.join(')(?=.*') + ')'
@contacts = Contact.where({name: /#{regex}/i })

#2


0  

You can use $regex from monogDB.

您可以使用monogDB中的$ regex。

Collection.where(name: {'$regex': params[:search], '$options': 'i'})

it will return all the data similar to name string.

它将返回类似于name string的所有数据。