首页 > 解决方案 > 查询数组时出现 MongoDB 数据匹配和获取问题

问题描述

我想从 MongoDB 中获取数据。因为我是 Node.Js 和 MongoDB 的新手。我无法获取数据。

我将主要类别和次要类别传递给一个 API,我想在其中将主要和次要类别与具有两个索引 0 和 1 的数组字段“类别”匹配,在 0 索引中主要类别存在并且在 1 索引中次要类别由 ~ 分隔。

下面是我根据主要类别获取数据的代码,但我想通过匹配数据库中的主要和次要类别来获取数据。

ProductModel
.find({ category : { $all : [req.body.primary] }})
.select('id link brand title description category image images in_stock price sale_price merchant_number part_number GroupID status promotion attributes tags currency updated -_id')
.then((productList) => {
  response.status = 200;
  response.msg = 'Success';
  response.count = productList.length;
  response.data = productList
  res.json(response);
})
.catch(() => {
  response.status = 500;
  response.msg = 'connection error';
  response.data = [];
  res.json(response);
});

样本文件:

数据库结构截图

所以我想输入类似['Health','women']& get docs 之类的东西,其中类别数组中的所有这些元素都存在,一种对数组元素的正则表达式搜索。

有人可以帮我从数据库中获取数据吗?

标签: node.jsmongodbmongoosemongodb-query

解决方案


如果您必须使用输入进行查询并['Health', 'women']获取已列出的文档并获取具有以下内容的文档:category : ["Health", "tes~men~women"]那么您可以尝试以下查询:

询问 :

db.collection.find({
  $and: [
    {
      category: {
        $in: [
          /\bwomen\b/
        ]
      }
    },
    {
      category: {
        $in: [
          "Health"
        ]
      }
    }
  ]
})

JS代码:

const secondary = req.body.secondary
const primary = req.body.primary
db.collection.find({
    $and: [
        {
            category: {
                $in: [
                    new RegExp(`\\b${secondary}\\b`, 'i')
                ]
            }
        },
        {
            category: {
                $in: [
                    primary
                ]
            }
        }
    ]
})

推荐阅读