是否可以在 $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-" }

更新於:2020-03-30

74 瀏覽量

開啟你的 職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.