Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

236
Vistas
Mongoose aggregation pipeline: Comparing to own object

I have a sample mongoose object that looks like this:

  {
    _id: 5fa849ad4f6be0382363809c,
    ratings: {
      ratedPersonId: 7,
      rating: 7,
      timeSpent: 30,
      timestamp: 78,
      userThreshold: 5
    }
  },

it contains an _id and a list of ratings which is a subdocument with the following features.

I have created an aggregation pipeline like this:

    const ratedUser = await this.ratingModel
      .aggregate([
        { $project: { ratings: 1 } },
        { $unwind: '$ratings' },
        {
          $match: {
            $and: [{ 'ratings.ratedPersonId': userId }, { 'ratings.rating': { $gte: 5 } }],
          },
        },
      ])
      .exec()

This works for the first condition ratings.ratedPersonId: userId

My problem is that my second condition is the rating should be greater than or equal to the userThreshold field in the same object.

whenever I type that in the query it returns nothing

 $and: [{ 'ratings.ratedPersonId': userId }, { 'ratings.rating': { $gte: 'ratings.threshold'} }],

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Demo - https://mongoplayground.net/p/AQMsJGkoFcu

Use $expr to compare the fields

Read aggregation-expressions

$expr can build query expressions that compare fields from the same document in a $match stage. If the $match stage is part of a $lookup stage, $expr can compare fields using let variables. See Specify Multiple Join Conditions with $lookup for an example. $expr only uses indexes on the from the collection for equality matches in a $match stage. $expr does not support multikey indexes.

db.collection.aggregate([
  {
    $project: {
      ratings: 1
    }
  },
  {
    $unwind: "$ratings"
  },
  {
    $match: {
      $and: [
        {
          "ratings.ratedPersonId": 7
        },
        {
          $expr: {
            $gte: [
              "$ratings.rating",
              "$ratings.userThreshold"
            ]
          }
        }
      ],
      
    },
  },
])
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda