Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!