简体   繁体   English

获取数组的至少一个元素包含 substring 的文档

[英]Fetch documents where at least one element of an array contains a substring

I have a document of the following form in MongoDB:我在 MongoDB 中有以下形式的文档:

product = {
    items : Array
}

....sample ....样本

{
   "items": ["bananas","apples","grapes","guavas","pineapples"]
}

I want to fetch all documents where one of the items' elements contains a substring called apple我想获取其中一个项目元素包含名为apple的 substring 的所有文档

Ideally, apples and pineapples in the array contain the substring apple so the document is supposed to match.理想情况下,数组中的applespineapples包含 substring apple ,因此文档应该匹配。

What I've tried with no success我尝试过的没有成功

let prods = await Product.find({items: {"$in":["apple"]}); //But not working

Any ideas of a better way would be appreciated.任何更好的方法的想法将不胜感激。

Thanks谢谢

You simply need to check regular expression condition,您只需要检查正则表达式条件,

  • use $regex operator to check the condition使用$regex运算符检查条件
let prods = await Product.find({
  items: {
    $regex: "apple"
  }
});

Playground操场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Mongodb:查找具有至少一个元素与ObjectID不匹配的数组的文档 - Mongodb: Find documents with array where at least one element does not match ObjectID 如何查询数组字段至少有一个属性等于'X'的对象元素的所有文档? - How to query all documents where array field have at least one object-element with property equal 'X'? Mongodb:查找所有至少一个数组元素不匹配的文档? - Mongodb: Find all documents where at least one array element does not matches? Mongoose 查找数组包含至少一个与 id 匹配的对象的位置 - Mongoose find where array contains at least one object that matches with an id MongoDB获取具有至少一个非空数组的文档 - MongoDB get documents with at least one not empty array 如何检查数组是否包含至少一个对象? - How to check if array contains at least one object ? MongoDB-查找至少缺少一个数组值的位置 - MongoDB - Find where at least one array value is missing NodeJS MongoDB 其中 Array 包含 Array 的任何元素 - NodeJS MongoDB Where Array contains any element of Array 如何从给定的项目数组中找到其数据与至少一个项目的条件匹配的文档 - mongoDB - How to find documents that their data match a condition on at least one item from a given array of items - mongoDB 一种高效且异步的方法来检查数组的至少一个元素是否也是另一个数组的元素 - Efficient and async way to check if at least one element of an array is also an element of another array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM