如何在 Mongodb 的字段中查找子字符串 [英] How to find a substring in a field in Mongodb

查看:14
本文介绍了如何在 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:

我想在 db数据库"中查找所有对象,其中 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屋!

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