如何加入然后对猫鼬进行查询

问题描述 投票:1回答:1

假设我有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 }
}

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

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”搜索关键字以在“藏书”中查询时它将返回:

   _id     name     author
   1       BookA    1        (because author 1 name "Foo")
   2       Foo      2
node.js database mongodb mongoose
1个回答
1
投票

以下查询将有所帮助:

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中进行的,您可以轻松地将其转换为所需的查询。

© www.soinside.com 2019 - 2024. All rights reserved.