Quoc Van Tang
Quoc Van Tang

Reputation: 1193

How to join then perform query on mongoose

Suppose I have 2 Schema

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

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

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: If I have

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

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

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

Upvotes: 1

Views: 268

Answers (1)

ngShravil.py
ngShravil.py

Reputation: 5048

The following query will be helpful:

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
    }
  }
])

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

Upvotes: 1

Related Questions