本文介绍了如何加入然后对猫鼬进行查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有2个架构

// User
{
  name: { type: Types.Name, required: true, index: true }
}

// Book
{
  name: { type: Types.String, index: true },
  author: { type: Types.Relationship, ref: 'User', index: true }
}

我想使用名称"字段和"author.name"字段之间的OR运算符对Book模式执行搜索查询(这意味着如果我输入"abc"搜索,它将返回名称包括"abc"的所有Book"或书名"的作者包括"abc").我该如何实现?感谢您的帮助,谢谢.

I want to perform a search query on Book schema with OR operator between "name" field and "author.name" field (It means if I input "abc" search, it will return any Books with the name include "abc" or Books' author with the name include "abc"). How can I achieve that? I appreciate any helps, thanks in advance.

P/S:如果我有

User Collection
_id     name
1       Foo
2       Bar
3       XYZ

Book Collection
_id     name     author
1       BookA    1
2       Foo      2
3       BookC    2
4       BookD    3

因此,当我输入"Foo"搜索键以在Book Collection中进行查询时它将返回:

So when I input "Foo" search key to query in Book CollectionIt will return:

   _id     name     author
   1       BookA    1        (because author 1 name "Foo")
   2       Foo      2

推荐答案

以下查询将很有帮助:

db.Book.aggregate([
  {
    $lookup: {
      from: "User",
      localField: "author",
      foreignField: "_id",
      as: "user"
    }
  },
  {
    $unwind: {
      path: "$user",
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $match: {
      $expr: {
        $or: [
          {
            $eq: [
              "$name",
              "Foo" // Replace with your search string.
            ]
          },
          {
            $eq: [
              "$user.name",
              "Foo" // Replace with your search string.
            ]
          }
        ]
      }
    }
  },
  {
    $project: {
      name: 1,
      author: 1
    }
  }
])

注意:上面的查询是在纯Mongo中进行的,您可以轻松地将其转换为所需的查询.

Note: The above query is in pure Mongo, you can easily convert it to your required one.

这篇关于如何加入然后对猫鼬进行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:38
查看更多