简体   繁体   中英

MongoDB search string in array of objects

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 command, 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?

您可以使用items.value点符号来定位所有items元素的value字段,并使用正则表达式执行不区分大小写的子字符串匹配:

db.getCollection('docs').find({ 'items.value': /text/i })

You can use the $elemMatch ( https://docs.mongodb.com/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 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM