Home > Software design >  How to query for the occurrence of an element in the array in mongo DB aggregation pipeline
How to query for the occurrence of an element in the array in mongo DB aggregation pipeline

Time:09-29

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.

CodePudding user response:

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

  • Related