$in requires an array as a second argument, found: missing

后端 未结 1 491
青春惊慌失措
青春惊慌失措 2020-11-27 22:59

can anybody please tell me what am i doing wrong?

db document structure:

{
    \"_id\" : \"module_settings\",
    \"moduleChildren\" : [
        {
           


        
相关标签:
1条回答
  • 2020-11-27 23:27

    First option --> Use aggregation

    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.

    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" ]
            }
          }
        }
      }}
    ])
    

    Second option -->

    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 }
    )
    
    0 讨论(0)
提交回复
热议问题