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

160
Vistas
How to query for the occurrence of an element in the array in mongo DB aggregation pipeline

I'm using mongoose to connect to Mongo DB.

At first this is my schema:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const TestSchema = new Schema({
  story: String,
  seenByUser: [String],
  medicationStage: {
    type: String,
    enum: [
      "no-medication",
      "just-after-medication",
      "towards-end-of-medication",
    ],
    required: true,
  },
});

// Compile model from schema
const TestModel = mongoose.model("Test", TestSchema);

module.exports = {
  Test: TestModel,
};

Here you can see I have a field called seenByUser which is an array of strings that is an array of user names. I'm setting up a data aggregation pipeline where I want to see given a user name fetch me all the documents where this user Name does not occur in seenByUser array. grouped by medicationStage. I'm unable to create this pipeline. Please help me out.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

If I've undesrtood correctly you can try this aggregation:

  • First $match where does not exists yourValue into the array seenByUser.
  • Then $group by medicationStage. This create a nested array (because $push add the whole array)
  • And $project to use $reduce and flat the array.
db.collection.aggregate({
  "$match": {
    "seenByUser": {
      "$ne": yourValue
    }
  }
},
{
  "$group": {
    "_id": "$medicationStage",
    "seenByUser": {
      "$push": "$seenByUser"
    }
  }
},
{
  "$project": {
    "_id": 0,
    "medicationStage": "$_id",
    "seenByUser": {
      "$reduce": {
        "input": "$seenByUser",
        "initialValue": [],
        "in": {
          "$concatArrays": [
            "$$value",
            "$$this"
          ]
        }
      }
    }
  }
})

Example here

about 4 years ago · Juan Pablo Isaza 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