Search must not include ObjectId

Hi, I’m in the process of refactoring a $match to the various parts of a $search.

As an example, this works:

$search: {
  index: 'assets',
  compound: {
    must: [
      {
        equals: {
          path: 'isActive',
          value: 3
        },
      },
      {
        text: {
          path: 'userId',
          query: userId
        }
      },
    ]
  }
}

… while this does not:

$search: {
  index: 'assets',
  compound: {
    must: [
      {
        equals: {
          path: 'isActive',
          value: 3
        },
      },
      {
        text: {
          path: 'userId',
          query: userId
        }
      },
    ],
    mustNot: [
      {
        equals: {
          path: '_id',
          value: assetId
        },
      },
    ]
  }
}

Here, “userId” is a string representation of an ObjectId, but anything involving an actual ObjectId fails when used in the $search, while the $match works:

$match: {
  _id: {
    $ne: assetId
  }
}

I’m also using a $project:

const project = {
  $project: {
    _id: 0,
    id: '$_id',
    userId: 1,
  }
}

I’ve tried changing the “_id” around and experimenting, (“$_id”, “id” and so on) but nothing has worked.

Any ideas?

Hi @Wayne_Smallman , can you clarify what you mean be “anything involving an actual ObjectId fails”? Does the query return an error, or nothing matches?

Depending on the interface or MongoDB driver you are using, it could be related to the type of assetId as it may require the ObjectId wrapper, see example here.

Hi @amyjian, nothing matches.

I’m using the exact same variable in the $match as I am in the $search, so it’s not related to type.

According to the documentation, mustNot:

Clauses that must not match for a document to be included in the results. mustNot clauses don’t contribute to a returned document’s score.

I’m struggling to understand the purpose of having it, if it’s sole purpose is to not change the score.

How am I supposed to replicate the $match?