简体   繁体   中英

Filter MongoDB autocomplete

When building an autocomplete aggregation pipeline using MongoDb Atlas search indexes. How do I limit the autocomplete to only search through specific ID's?

I'm building search functionality where a user can search for people and the application should autocomplete the search but the user should only be suggested users that it is allowed to view.

My pipeline (works but need to be filtered):

{
  'compound': {
    'should': [{
      'autocomplete': {
        'query': "John",
        'path': 'firstName'
      }
    }, {
      'autocomplete': {
        'query': "Doe",
        'path': 'lastName'
      }
    },
    ]
  }
}

If I have an array of people Id:s that the user can view, how do I go about only applying the autocomplete search on the people with the ID:s I supply?

Something like {_id: {$in myIdList}}

You can use the equals operator to match on an ObjectID. Specifically, in the must clause of your current Compound query, nest another Compound query which has 1 should clause per ObjectID you would like to filter for. Each should clause would be defined as an equals operator for a specific ObjectID. I can provide an example of how it would look like if needed. Also, just a reminder that the field that contains an array of ObjectID's needs to be indexed in Atlas Search so you can use the equals operator on it.

I would consider adding a filter clause to your compound query like so:

{
  'compound': {
    'filter': {
      text': {
        'query': userId,
        'path': 'userId'
      }
    }
    'should': [{
      'autocomplete': {
        'query': "John",
        'path': 'firstName'
      }
    }, {
      'autocomplete': {
        'query': "Doe",
        'path': 'lastName'
      }
    },
    ]
  }
}

There's a great example here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM