$in 需要一个数组作为第二个参数,发现:缺失 [英] $in requires an array as a second argument, found: missing

查看:33
本文介绍了$in 需要一个数组作为第二个参数,发现:缺失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我我做错了什么?

can anybody please tell me what am i doing wrong?

db文档结构:

{
    "_id" : "module_settings",
    "moduleChildren" : [
        {
            "_id" : "module_settings_general",
            "name" : "General",
        },
        {
            "_id" : "module_settings_users",
            "name" : "Users",
        },
        {
            "_id" : "module_settings_emails",
            "name" : "Emails",
        }
    ],
    "permissions" : [
        "module_settings_general",
        "module_settings_emails"
    ]
}

管道阶段:

{ $project: {
    filteredChildren: {
        $filter: {
           input: "$moduleChildren",
           as: "moduleChild",
           cond: { $in : ["$$moduleChild._id", "$permissions"] }
        }
    },
}}

我需要过滤moduleChildren"数组以仅显示 ID 位于permissions"数组中的模块.我试过$$ROOT.permissions"和$$CURRENT.permissions",但它们都不起作用.我总是收到 $in 缺少数组作为参数的错误.当我像这样对数组进行硬编码时,它可以工作: cond: { $in : ["$$moduleChild._id", ["module_settings_general", "module_settings_emails"]] } 所以看来问题出在数组的传递.感谢您的任何建议!

I need to filter "moduleChildren" array to show only modules which ids are in "permissions" array. Ive tried "$$ROOT.permissions" and "$$CURRENT.permissions" but none of them is working. I always get an error that $in is missing array as argument. It works when i hardcode the array like this: cond: { $in : ["$$moduleChild._id", ["module_settings_general", "module_settings_emails"]] } so it seems the problem is in passing of the array. Thanks for any advices!

推荐答案

第一个选项 --> 使用聚合

因为您的集合中的某些文档可能包含也可能不包含 permissions 字段,或者类型不等于数组,这就是您收到此错误的原因.

Because your some of the documents in your collection may or may not contain permissions field or is type not equal to array that's why you are getting this error.

您可以找到 $type 字段,如果它不是数组或文档中不存在,则可以使用 $addFields$cond 聚合

You can find the $type of the field and if it is not an array or not exists in your document than you can add it as an array with $addFields and $cond aggregation

db.collection.aggregate([
  { "$addFields": {
    "permissions": {
      "$cond": {
        "if": {
          "$ne": [ { "$type": "$permissions" }, "array" ]
        },
        "then": [],
        "else": "$permissions"
      }
    }
  }},
  { "$project": {
    "filteredChildren": {
      "$filter": {
        "input": "$moduleChildren",
        "as": "moduleChild",
        "cond": {
          "$in": [ "$$moduleChild._id", "$permissions" ]
        }
      }
    }
  }}
])

第二个选项 -->

在您使用的任何 GUI 上转到您的 mongo shell 或 robomongo 并运行这个命令

Go to your mongo shell or robomongo on any GUI you are using and run this command

db.collection.update(
  { "permissions": { "$ne": { "$type": "array" } } },
  { "$set": { "permissions": [] } },
  { "multi": true }
)

这篇关于$in 需要一个数组作为第二个参数,发现:缺失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆