3

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

This should be marked the correct answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.