【问题标题】:How to query for the occurrence of an element in the array in mongo DB aggregation pipeline如何在mongoDB聚合管道中查询数组中元素的出现
【发布时间】:2021-11-17 11:36:18
【问题描述】:

我正在使用 mongoose 连接到 Mongo DB。

起初这是我的架构:

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,
};

在这里您可以看到我有一个名为seenByUser 的字段,它是一个字符串数组,它是一个用户名数组。我正在设置一个数据聚合管道,我想在其中查看给定用户名获取该用户名的所有文档 不出现 @987654323 @ 大批。按medicationStage 分组。我无法创建此管道。请帮帮我。

【问题讨论】:

    标签: javascript mongodb mongoose aggregation-framework mongoose-schema


    【解决方案1】:

    如果我没理解错,你可以试试这个聚合:

    • 将不存在yourValue$match 放入数组seenByUser
    • 然后$groupmedicationStage。这会创建一个嵌套数组(因为$push 添加整个数组)
    • $project 使用$reduce 并展平阵列。
    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"
              ]
            }
          }
        }
      }
    })
    

    例如here

    【讨论】:

      猜你喜欢
      • 2018-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 1970-01-01
      • 2020-12-12
      • 2017-03-07
      • 2020-12-17
      相关资源
      最近更新 更多