簡體   English   中英

MongoDB 使用正則表達式過濾動態鍵和值的文檔

[英]MongoDB filter docs on dynamic key and value using regex

假設我在一個文檔中有多個字段我不知道其鍵值(只有添加了鍵的用戶才知道)

現在假設用戶想要找到一個指定鍵值的文檔,但他忘記了他的鍵值是什么

所以說我有這個文件:

name: "John Doe"
class: 5
MisChief: "Bullying"

MisChief 鍵是自定義創建的。

假設用戶想要搜索“惡作劇:欺凌”

我可以使用$regex運算符來搜索值,但是如何將鍵指定為正則表達式

另一種方法是返回所有文檔,並對所有這些文檔中的鍵進行不區分大小寫的搜索,這是非常低效的。

因此,對於未知/動態/隨機鍵名,一種使用聚合運算符$objectToArray的方法:

db.collection.aggregate([
  /** Add a new array field to all docs which contains each field as {k:...,v:...} */
  {
    $addFields: { data: { $objectToArray: "$$ROOT" } }
  },
  /** Match docs that has an object in `data` array which matches with input */
  {
    $match: { "data": { "$elemMatch": { "k": "MisChief", "v": "Bullying" } } } // can be a regex /MisChief/i
  },
  /** Remove added array field from output */
  {
    $project: { "data": 0 }
  }
])

測試: mongoplayground

參考:聚合

從你的陳述中:

but he forgot what his key value was EXACTLY

如果他模糊地記得鍵名/值但不完全記得 - 您可以根據需要使用正則表達式! 但是,如果他完全忘記了,那么您將無能為力,只需獲取data.v: 'Bullying'所有文檔並使用$match階段進一步過濾用戶name

db.collection.aggregate([
  {
    $addFields: { data: { $objectToArray: "$$ROOT" } }
  },
  {
    $match: { "data": { "$elemMatch": { "v": "Bullying" } } } 
  },
  {
    $project: { "data": 0 }
  }
])

測試: mongoplayground

筆記:

對於單個元素{ "v": "Bullying" } ,我們不需要使用$elemMatch ,但為了保持語法一致,我們正在使用它,否則您可以在$match階段使用data.v: 'Bullying'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM