是否可以将 MongoDB 字段值用作 `$regex` 中的模式?
可以,要实现这一点,请在聚合框架中使用 $indexOfCP 运算符。我们先创建一个包含文档的集合 -
> db.patterDemo.insertOne(
{
"ClientName": "John", "ClientWebsiteName":"webbuziness.com/John/business"
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cea40acef71edecf6a1f68d")
}
> db.patterDemo.insertOne(
{
"ClientName": "Carol", "ClientWebsiteName":"solvecoding.com/business"
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cea40acef71edecf6a1f68e")
}以下是通过 find() 方法显示集合中所有文档的查询 -
> db.patterDemo.find().pretty();
这将生成以下输出 -
{
"_id" : ObjectId("5cea40acef71edecf6a1f68d"),
"ClientName" : "John",
"ClientWebsiteName" : "abcd.com"
}
{
"_id" : ObjectId("5cea40acef71edecf6a1f68e"),
"ClientName" : "Carol",
"ClientWebsiteName" : "pqrs.com"
}以下是将字段值用作 $regex 中的模式的查询 -
> db.patterDemo.aggregate([ { "$match": { "$expr": { "$ne": [ { "$indexOfCP": ["$ClientWebsiteName", "$ClientName"] }, -1 ] } }} ]);这将生成以下输出 -
{ "_id" : ObjectId("5cea40acef71edecf6a1f68d"), "ClientName" : "John", "ClientWebsiteName" : "abcd.com" }
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP