【问题标题】:how to use join and like mysql in mongodb如何在mongodb中使用join和like mysql
【发布时间】:2020-02-19 21:07:08
【问题描述】:
var query = req.params.query;
const messages = await Message.aggregate([

      {
        $lookup: {
          from: 'users',
          localField: 'reference_id',
          foreignField: '_id',
          as: 'users'
        }
      },

      {'text': {'$regex': `.*${query}.*`}}
    ])

收到错误“消息”:“参数必须是聚合管道运算符”,

我想从 users 表中加入 first_name 和 last_name,并根据 first_name、last_name 和 text 进行搜索,我该如何实现这一目标

【问题讨论】:

  • 加入收藏或搜索时出现问题?
  • 加入它得到问题如何使它正确,希望你理解我的问题
  • @Shivam : text 也是用户集合或message 集合中的字段吗?
  • 是的文本是消息集合中的字段
  • 只是让这个问题和那里的答案一样重复,how to work with $lookup and $regex search in mongodb

标签: mongodb


【解决方案1】:

发生错误是因为“文本”不是聚合管道运算符。

您可以在 $match 阶段中使用 $text。详情请见https://docs.mongodb.com/manual/tutorial/text-search-in-aggregation/

我发现在 MongoDB Atlas (cloud.mongodb.com) 内部的聚合管道构建器中或使用 MongoDB Compass (https://www.mongodb.com/products/compass) 构建管道很有帮助,这样您就可以直观地看到管道每个阶段发生的情况.

【讨论】:

    【解决方案2】:
    function xyz = () => {
    return new Promise((resolve, reject) => {
    var query = req.params.query;
    var aggregate = Message.aggregate();
     aggregate
            .lookup({
              from: 'users',
              localField: 'reference_id',
              foreignField: '_id',
              as: 'users'
            })
            .match({
               $text: {$search: "$query"}
            )}
             aggregate.exec(function(err, result) {
             if (err) return reject(err);
             return resolve(result);
        });
    });
    }
    

    确保您的 localField id 和外部字段 id 匹配。 希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-26
      • 2012-03-14
      • 2015-05-26
      • 2012-05-28
      • 2011-10-18
      • 1970-01-01
      • 2016-09-13
      • 1970-01-01
      相关资源
      最近更新 更多