How to query MongoDB aggregate with collation option
Asked Answered
T

1

13

I created a "brands" collection and then added an index collation: { locale: "en", strength: 2} on the "title" field. But when I try to query it using this collation it doesn't work as expected:

const query = brand => mongodb.db("my-db").collection("brands")
    .aggregate([
      { $match: { title: brand } },
      { $project: { _id: 0, total: 1, categories: { $slice: [ "$categories", 5 ] }, tags: { $slice: [ "$tags", 5 ] } } }
    ], { collation: { locale: 'en', strength: 2 } })
    .asArray();

so calling brand('Test') gives results but brand('test') gives an empty list.

When I try the same query using Atlas Aggregation Builder both queries give the same (non-empty) result. Any ideas?

Tamasha answered 14/7, 2021 at 9:39 Comment(1)
It is not clear in what tools/environment the above query is being run. The syntax to specify collation varies depending upon the driver / ODM you are using. For example, code using NodeJS driver or MongoDB shell uses the collation option document to specify the collation: { collation: { locale: 'en', strength: 2 } }, (and this is as in the question post). If you are using Mongoose ODM, collation is specified as Model.aggregate(...).collation( { ... } ).Breed
C
0

Collation options can be used when using an aggregation pipeline in MongoDB, but it should be put as another option after the aggregate, rather than inside of the aggregate :)

const query = brand => mongodb.db("my-db").collection("brands")
.aggregate([
  { $match: { title: brand } },
  { $project: { _id: 0, total: 1, categories: { $slice: [ "$categories", 5 ] }, tags: { $slice: [ "$tags", 5 ] } } },
]).collation({locale: 'en', strength: 2})
.asArray();
Caricature answered 13/5 at 20:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.