2015-09-11 79 views
1

我在MongoDB中有一些偶爾包含不同類型的子文檔 - 字符串,另一個子文檔,另一個嵌套子文檔等。 我試圖構建一個查詢,子文檔內容,無論它是什麼類型。如何在不同的地方搜索MongoDB嵌套子文檔

考慮下列文件:

{ name: "test1", content: "test contents"} 
{ name: "test2", content: {family: "tests family content", last: "another test content"} } 
{ name: "test3", content: {subdocument: {family: "super family contents", last: "last test content"} } } 

我想用一個查詢,將所有文件和子文件中的所有字符串內進行搜索。 已經嘗試過下面的查詢,但它僅返回子文檔的最嵌套層次 - content.subdocument.family

{ $or: [ 
    {"content": {'$regex': '.*conten.*', '$options': 'i'}}, 
    {"content.family": {'$regex': '.*conten.*', '$options': 'i'}}, 
    {"content.last": {'$regex': '.*conten.*', '$options': 'i'}}, 
    {"content.subdocument.family": {'$regex': '.*conten.*', '$options': 'i'}}, 
    {"content.subdocument.last": {'$regex': '.*conten.*', '$options': 'i'}} 
]} 

是否有可能創建一個查詢,將遍歷所有嵌套的字符串\深處一次?

+0

這是非常不清楚你在問什麼。請閱讀[如何問](http://stackoverflow.com/help/how-to-ask)一個很好的問題,並使用[編輯鏈接](http://stackoverflow.com/posts/32521668/edit)來改善你的問題。 – styvane

+0

試圖編輯標題,介紹和問題,希望現在更好... – Do5

+0

順便說一句,作爲一種解決方法,我問用戶什麼深度,他想搜索。否則,它也可以創建3個不同的查詢,然後再檢查答案 – Do5

回答

0

這裏您缺少$or的語法$regex。您應該使用$or類似以下內容:

db.collection.find({ 
    $or: [{ 
    "content": { 
     '$regex': '.*conten.*', 
     '$options': 'i' 
    } 
    }, { 
    "content.family": { 
     '$regex': '.*conten.*', 
     '$options': 'i' 
    } 
    }, { 
    "content.last": { 
     '$regex': '.*conten.*', 
     '$options': 'i' 
    } 
    }, { 
    "content.subdocument.family": { 
     '$regex': '.*conten.*', 
     '$options': 'i' 
    } 
    }, { 
    "content.subdocument.last": { 
     '$regex': '.*conten.*', 
     '$options': 'i' 
    } 
    }] 
}) 

編輯:

上面的查詢給出以下結果:

[{ 
    "_id": ObjectId("55f41b6aef4766c946112a2d"), 
    "name": "test1", 
    "content": "test contents" 
}, { 
    "_id": ObjectId("55f41b6aef4766c946112a2e"), 
    "name": "test2", 
    "content": { 
    "family": "tests family content", 
    "last": "another test content" 
    } 
}, { 
    "_id": ObjectId("55f41b6aef4766c946112a2f"), 
    "name": "test3", 
    "content": { 
    "subdocument": { 
     "family": "super family contents", 
     "last": "last test content" 
    } 
    } 
}] 
+0

你是對的,但這只是一個錯字,不幸的是它不能解決問題。 – Do5

+0

@ Do5你想要什麼確切的輸出? – Vishwas

+0

我希望能夠在「內容」中的所有可能字段中搜索字符串。輸出結構不太相關,它可能是整個文檔,只有相關的字段或只有相關的子文檔,這並不重要 – Do5