Prabin
Prabin

Reputation: 69

MongoDB: Search Query to return an object inside the array

I have a Journal Schema which contains an array of notes. I want to implement MongoDB search in my application so that it returns the note that matches the query. Right now it returns the entire Journal Object which contains the matched note.

Journal Schema:

{
  userid: {
    type: String,
    required: true,
  },
  notes: [
    {
      content: {
        type: String,
      },
    },
  ],
}

Right now my query syntax is:

[
  {
    $search: {
      index: 'Journal-search-index',
      text: {
        query: 'asdf',
        path: 'content'
      }
    }
  }
]

It returns the entire Journal object but I only want the note that matches the query. is there any way to implement that?

Upvotes: 3

Views: 158

Answers (1)

semperlabs
semperlabs

Reputation: 458

You are currently searching for documents that match current query, but not filtering the data inside of documents, particulary notes array.

You have to add filter on the next aggregation operation

const query = "asdf";

db.collection.aggregate([
  {
    $search: {
      index: "Journal-search-index",
      text: {
        query: query,
        path: "content",
      },
    },
  },
  {
    $project: {
      notes: {
        $filter: {
          input: "$notes",
          as: "note",
          cond: {
            $regexMatch: {
              input: "$$note",
              regex: query,
              options: "i",
            },
          },
        },
      },
    },
  },
]);

Playground Example

Upvotes: 2

Related Questions