[英]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.