[英]MongoDB search string in array of objects
我在MongoDB中有一個結構,該結構在稱為“項目”的數組中具有不同數量的項目。 為了進行搜索,我使用以下命令,該命令首先將內容轉換為字符串,例如this.items根據對象存在不同的結構:
db.getCollection('docs').find.('JSON.stringify(this.items[0].value).toLowerCase().indexOf("text")!=-1')
我的問題是,由於我不知道每個文檔的項目數量,因此我必須使用通配符作為this.items [*]。value,但它不起作用。
有誰知道任何解決方案,或對此有其他想法?
您可以使用items.value
點符號來定位所有items
元素的value
字段,並使用正則表達式執行不區分大小寫的子字符串匹配:
db.getCollection('docs').find({ 'items.value': /text/i })
您可以使用$ elemMatch( https://docs.mongodb.com/manual/reference/operator/projection/elemMatch/ )
db.docs.find({items: {$elemMatch: {value: {$regex : "text"}}}});
因此,此查詢將在items數組中找到所有帶有item
文檔,這些文檔的value屬性中包含字符串“ text”,執行此操作后,您可以計算該文檔有多少項目。
您可以迭代每個文檔並應用indexOf
,類似這樣。
var cursor = db.getCollection('docs').find({}); // get all docs
var newOut = []; // new array of items if match with some condition
while ( cursor.hasNext() ){ // iterate all docs
var doc = cursor.next(); // get the document in focus
doc.items.forEach(function(item){ // iterate the items of doc.items
if ( item.toLowerCase().indexOf("text") !== -1 ) // check if text exists in array
newOut.push(item); // add to new array
});
};
printjson(newOut);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.