1

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.