String field value length in array in mongoDB

那年仲夏 提交于 2020-01-04 04:05:30

问题


How can I get the length of characters from a field that is nested in another field? and it is in an array. eg:

{
    "_id" : ObjectId("687e1db"),
    "content" : {
        "ods" : "1102223000241",
        "startDate" : ISODate("2017-05-11T12:00:00Z"),
        "classes" : [
            {
              "driveNumber" : "9999078900007091",
              "number" : "00107605829357",
              "sId" : "0000000005009593"
            }
        ],
         "user" : "SoftLogic",
    },
    "level" : 2
}

and I want to get a sample in the content.classes.number, where there are more than 16 characters in the field.

when making a request I was guided by String field value length in mongoDB

Either this request is not suitable for this situation, or I am doing something wrong.

db.Basis.find({
    "content.classes.number": { "$exists": true }, 
    "$expr": { "$gt": [ { "$strLenCP": "$content.classes.number" }, 16 ] }})

I get the error: https://gyazo.com/d2849406d36364de94d6ea89eff1c2b6

I tried not only such options.

UPD mongo version 3.4.3


回答1:


content.classes.number is an array field not a string and that's why your query could not work.

One solution here is to use $arrayElemAt operator but don't know which element you want to check with. But for instance, I am taking the 0th element here.

db.Basis.find({
  "content.classes.number": { "$exists": true }, 
  "$expr": { "$gt": [{ "$strLenCP": { "$arrayElemAt": ["$content.classes.number", 0] }}, 16 ] }
})


来源:https://stackoverflow.com/questions/55580988/string-field-value-length-in-array-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!