如何在Mongodb中的字段中查找子字符串 [英] How to find a substring in a field in Mongodb
问题描述
如何找到数据库中所有包含对象子字段的对象?
How can I find all the objects in a database with where a field of a object contains a substring?
如果该字段在具有字符串值的集合对象中为A:
If the field is A in an object of a collection with a string value:
我想在数据库数据库"中找到所有对象,其中A包含一个子字符串,例如"abc def".
I want to find all the objects in the db "database" where A contains a substring say "abc def".
我尝试过:
db.database.find({A: {$regex: '/^*(abc def)*$/''}})
但是没用
更新
真实的字符串(采用unicode):
A real string (in unicode):
Sujet Commentaire sur Star Wars Episode III - La Revanche des Sith 1
需要搜索与《星球大战》相关的所有条目
Need to search for all entries with Star Wars
db.test.find({A: {$regex: '^*(star wars)*$''}}) not wokring
推荐答案
代替此:
db.database.find({A: {$regex: '/^*(abc def)*$/''}})
您应该这样做:
db.database.find({A: /abc def/i })
^ *实际上不是有效的语法,因为^和$是锚,而不是可重复的东西.您可能在这里的意思是^.*.但是并不需要^.*,因为它仅表示所有跟在后面的字符",而(abc def)*则表示"0或更多倍" abc def",但它必须在字符串的末尾,因为您的美元.结尾处的"i"是使其不区分大小写.
^* is not actually valid syntax as ^ and $ are anchors and not something that is repeatable. You probably meant ^.* here. But there is no need for ^.* as that simply means "Everything up to the character following" and (abc def)* means "0 or more times "abc def", but it has to be at the end of the string, because of your $. The "i" at the end is to make it case insensitive.
这篇关于如何在Mongodb中的字段中查找子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!