簡體   English   中英

MongoDB使用Java使用正則表達式查詢字段中的值

[英]MongoDB query for value in field with regex using Java

我正在嘗試從我的文檔集合中查詢:

{ "_id" : ObjectId("94"), "EmailAddress" :"adam@gmail.com","Interests": "CZ1001,CE2004" }
{ "_id" : ObjectId("44"), "EmailAddress" :"ben@gmail.com", "Interests":"CE1001,CE4002" }
{ "_id" : ObjectId("54"), "EmailAddress" :"chris@gmail.com","Interests":"CE1001,CE2002" }

一個示例是,由於字段“ Interests”具有我要查找的值,因此我想檢索電子郵件地址。

例如,如果我搜索CZ1001,我將獲得Obj 1 EmailAddress詳細信息。

如果我搜索CE1001,我將獲得Obj 2和Obj 3 EmailAddress的詳細信息。

如果有幫助,當我在開始時插入記錄時,對象ID是唯一創建的。

我可以使用以下方法在MongoDB Shell上獲取對象

db.users.find(Module: {"$regex": "CE1001"}})

只需要電子郵件地址。

我試圖獲取所有電子郵件地址,並被卡​​在此代碼中。

Document doc = (Document) collection.find(new BasicDBObject("Module", {"$regex":"CE1001"})) .projection(Projections.fields(Projections.include("EmailAddress"), Projections.excludeId())).first(); 

new BasicDBObject("Module", {"$regex":"CE1001"})

允許使用new BasicDBObject("Module", String_variable)

對於特定的Interest ,您的mongoDB查詢看起來像(以CE1001為例):

db.collection.find({
  $or: [
    {
      Interests: {
        $regex: "^CE1001,"
      }
    },
    {
      Interests: {
        $regex: ",CE1001,"
      }
    },
    {
      Interests: {
        $regex: ",CE1001$"
      }
    }
  ]
},
{
  "EmailAddress": 1
})

對於碰巧不喜歡此帖子的其他人。 以下是工作代碼。 致謝@Veeram。

FindIterable <Document> results = collection.find(new BasicDBObject("Module", new BasicDBObject("$regex", "CE1001")) .projection(Projections.fields(Projections.include("EmailAddress"), Projections.excludeId()));

for(Document doc : results) {
doc.getString("EmailAddress")
 }

暫無
暫無

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

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