如何通过查询过滤器在mongodb中搜索

时间:2019-02-15 09:20:21

标签: javascript mongodb

我的网站上有一张桌子,用户可以在其中在搜索字段中输入单词,我希望mongodb在特定对象中搜索这些单词,并仅返回匹配的对象。搜索文本在请求查询中发送。

我使用以下代码进行分页,但是缺少搜索功能。

const result = await orders.aggregate([
      { $facet: {
        rows: [
          { $match: { status: {
            $in: ['received', 'packing', 'packed', 'fulfilled', 'rejected', 'withdrawn'],
          },
          } },
          { $skip: offsetPage * parseInt(req.query.rowsPerPage) },
          { $limit: parseInt(req.query.rowsPerPage) },
          { $project: {
            record: 1,
            status: 1,
            onPalette: 1,
            note: 1,
            grossTotal: 1,
            receivedLog: 1,
            arrivalDate: 1,
            partner: 1,
            location: 1,
          } },
        ],
        count: [
          { $count: 'count' },
        ],
      } },
    ]).toArray();

我想在一个数字的“记录”字段中搜索,在一个字符串的伙伴名称“ partner.name”中搜索。

如果没有发送搜索查询,或者搜索查询(req.query.filter)为空字符串,则返回所有内容

1 个答案:

答案 0 :(得分:1)

{ "_id" : 1, "location" : "24th Street",
  "in_stock" : [ "apples", "oranges", "bananas" ] }
{ "_id" : 2, "location" : "36th Street",
  "in_stock" : [ "bananas", "pears", "grapes" ] }
{ "_id" : 3, "location" : "82nd Street",
  "in_stock" : [ "cantaloupes", "watermelons", "apples" ] }
db.fruit.aggregate([
  {
    $project: {
      "store location" : "$location",
      "has bananas" : {
        $in: [ "bananas", "$in_stock" ]
      }
    }
  }
])
OUTPUT --
{ "_id" : 1, "store location" : "24th Street", "has bananas" : true }
{ "_id" : 2, "store location" : "36th Street", "has bananas" : true }
{ "_id" : 3, "store location" : "82nd Street", "has bananas" : false }