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

时间:2020-05-27 04:02:28

标签: node.js database mongodb mongoose

假设我有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”)。我该如何实现?感谢您的帮助,谢谢。

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中进行查询时 它将返回:

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

1 个答案:

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