Javascript 对象数组中的MongoDB搜索字符串
我在MongoDB中有一个结构,在一个名为“items”的数组中有不同数量的项。要进行搜索,我使用以下命令,首先将内容转换为字符串,如下图所示。根据对象的不同,有不同的结构:Javascript 对象数组中的MongoDB搜索字符串,javascript,php,mongodb,Javascript,Php,Mongodb,我在MongoDB中有一个结构,在一个名为“items”的数组中有不同数量的项。要进行搜索,我使用以下命令,首先将内容转换为字符串,如下图所示。根据对象的不同,有不同的结构: db.getCollection('docs').find.('JSON.stringify(this.items[0].value).toLowerCase().indexOf("text")!=-1') 我的问题是,由于我不知道每个文档中有多少项,因此我必须使用通配符作为.items[*].value,但它不起作用
db.getCollection('docs').find.('JSON.stringify(this.items[0].value).toLowerCase().indexOf("text")!=-1')
我的问题是,由于我不知道每个文档中有多少项,因此我必须使用通配符作为.items[*].value,但它不起作用
是否有人知道任何解决方案,或者对此有其他想法?您可以使用$elemMatch()
因此,此查询将在包含value属性中的字符串“text”的items数组中查找包含
项的所有文档,在此操作后,您可以计算文档中有多少项 您可以使用$elemMatch()
因此,此查询将在包含value属性中的字符串“text”的items数组中查找包含项的所有文档,在此操作后,您可以计算文档中有多少项 您可以迭代每个文档并应用索引of
,如下所示
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);
您可以迭代每个文档并应用索引of
,如下所示
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);
您可以使用items.value
的点表示法以所有items
元素的value
字段为目标,并使用正则表达式执行不区分大小写的子字符串匹配:
db.getCollection('docs').find({ 'items.value': /text/i })
您可以使用items.value
的点表示法以所有items
元素的value
字段为目标,并使用正则表达式执行不区分大小写的子字符串匹配:
db.getCollection('docs').find({ 'items.value': /text/i })
getCollection('docs')。查找
而不是getCollection('docs')查找
getCollection('docs')。查找
而不是getCollection('docs')查找
我的问题是“text”是一个子字符串,而不是全文值。已更新;)您可以使用$regexWorked!非常感谢你!我的问题是“text”是一个子字符串,而不是全文值。Updated;)您可以使用$regexWorked!非常感谢你!和regex一起工作!非常感谢。和regex一起工作!非常感谢。