admin管理员组文章数量:1331230
I have a structure in MongoDB that have different amounts of items in an array called "items". To make the search, I am using the following mand, which first turns the contents into a string, as in this.items there is a different structure depending on the object:
db.getCollection('docs').find.('JSON.stringify(this.items[0].value).toLowerCase().indexOf("text")!=-1')
My problem is that as I do not know the amount of items that each document has, I would have to use a wildcard as this.items[*].value, but it does not work.
Does anyone know any solution, or have another idea for this?
I have a structure in MongoDB that have different amounts of items in an array called "items". To make the search, I am using the following mand, which first turns the contents into a string, as in this.items there is a different structure depending on the object:
db.getCollection('docs').find.('JSON.stringify(this.items[0].value).toLowerCase().indexOf("text")!=-1')
My problem is that as I do not know the amount of items that each document has, I would have to use a wildcard as this.items[*].value, but it does not work.
Does anyone know any solution, or have another idea for this?
Share Improve this question edited Oct 24, 2016 at 13:39 JohnnyHK 312k69 gold badges630 silver badges475 bronze badges asked Oct 24, 2016 at 12:48 SergioSergio 6191 gold badge7 silver badges11 bronze badges 1-
getCollection('docs').find
insteadgetCollection('docs')find
– BrTkCa Commented Oct 24, 2016 at 12:52
3 Answers
Reset to default 5You can use the $elemMatch (https://docs.mongodb./manual/reference/operator/projection/elemMatch/)
db.docs.find({items: {$elemMatch: {value: {$regex : "text"}}}});
So this query will find all documents with an item
in the items array that contain the string "text" in the value property, after this operation you can count how much items the document has.
You can use dot notation of items.value
to target the value
field of all items
elements, and a regular expression to perform the case-insensitive sub-string match:
db.getCollection('docs').find({ 'items.value': /text/i })
You can iterate each document and apply the indexOf
, something like this..
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);
本文标签: javascriptMongoDB search string in array of objectsStack Overflow
版权声明:本文标题:javascript - MongoDB search string in array of objects - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742248309a2440271.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论