是否可以在 $regex 中使用 MongoDB 表格字段值作为模式?
是的,你可以使用 $indexOfCP 来将字段值用作模式。我们来创建一个带有文档的集合 −
> db.demo88.insertOne(
... {
... "Name": "Chris",
... "PassoutYear": "2020",
... "websiteName": "chris.shop.com/Carol-2020-"
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2c14c471bf0181ecc422b1")
}
> db.demo88.insertOne(
... {
... "Name": "David",
... "PassoutYear": "2010",
... "websiteName": "david.bigshop.com/David-2010-"
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2c14c571bf0181ecc422b2")
}使用 find() 方法显示集合中的所有文档 −
> db.demo88.find();
这将生成以下输出 −
{ "_id" : ObjectId("5e2c14c471bf0181ecc422b1"), "Name" : "Chris", "PassoutYear" : "2020", "websiteName" : "chris.shop.com/Carol-2020-" }
{ "_id" : ObjectId("5e2c14c571bf0181ecc422b2"), "Name" : "David", "PassoutYear" : "2010", "websiteName" : "david.bigshop.com/David-2010-" }以下是在 $regex 中使用字段值作为模式的查询 −
> db.demo88.aggregate([ { "$match": { "$expr": { "$ne": [ { "$indexOfCP": ["$websiteName", "$Name"] }, -1 ] } }} ])这将生成以下输出 −
{ "_id" : ObjectId("5e2c14c571bf0181ecc422b2"), "Name" : "David", "PassoutYear" : "2010", "websiteName" : "david.bigshop.com/David-2010-" }
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP