MongoDB에서 특정 값보다 긴 길이의 문자열을 찾으려면 $where 연산자를 사용하세요. 구문은 다음과 같습니다 -
db.yourCollectionName.find({$where:'this.yourStringFieldName.length > yourIntegerValue'}).pretty();
위의 개념을 이해하기 위해 문서로 컬렉션을 만들어 보겠습니다. 문서로 컬렉션을 생성하는 쿼리는 다음과 같습니다 -
> db.stringFieldLengthDemo.insertOne({"UserId":1,"UserName":"Adam Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5c77bb4b2386c62d05142a78") } > db.stringFieldLengthDemo.insertOne({"UserId":2,"UserName":"Carol Taylor"}); { "acknowledged" : true, "insertedId" : ObjectId("5c77bb562386c62d05142a79") } > db.stringFieldLengthDemo.insertOne({"UserId":3,"UserName":"James Brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5c77bb5b2386c62d05142a7a") } > db.stringFieldLengthDemo.insertOne({"UserId":4,"UserName":"John Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5c77bb662386c62d05142a7b") } > db.stringFieldLengthDemo.insertOne({"UserId":5,"UserName":"David Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5c77bb892386c62d05142a7c") } > db.stringFieldLengthDemo.insertOne({"UserId":6,"UserName":"John Williams"}); { "acknowledged" : true, "insertedId" : ObjectId("5c77bbb02386c62d05142a7d") } > db.stringFieldLengthDemo.insertOne({"UserId":7,"UserName":"Chris Evans"}); { "acknowledged" : true, "insertedId" : ObjectId("5c77bbd32386c62d05142a7e") }
find() 메서드를 사용하여 컬렉션의 모든 문서를 표시합니다. 쿼리는 다음과 같습니다 -
> db.stringFieldLengthDemo.find().pretty();
다음은 출력입니다 -
{ "_id" : ObjectId("5c77bb4b2386c62d05142a78"), "UserId" : 1, "UserName" : "Adam Smith" } { "_id" : ObjectId("5c77bb562386c62d05142a79"), "UserId" : 2, "UserName" : "Carol Taylor" } { "_id" : ObjectId("5c77bb5b2386c62d05142a7a"), "UserId" : 3, "UserName" : "James Brown" } { "_id" : ObjectId("5c77bb662386c62d05142a7b"), "UserId" : 4, "UserName" : "John Smith" } { "_id" : ObjectId("5c77bb892386c62d05142a7c"), "UserId" : 5, "UserName" : "David Miller" } { "_id" : ObjectId("5c77bbb02386c62d05142a7d"), "UserId" : 6, "UserName" : "John Williams" } { "_id" : ObjectId("5c77bbd32386c62d05142a7e"), "UserId" : 7, "UserName" : "Chris Evans" }
다음은 MongoDB에서 11보다 긴 길이의 문자열을 찾는 쿼리입니다 -
> db.stringFieldLengthDemo.find({$where:'this.UserName.length >11'}).pretty();
다음은 출력입니다 -
{ "_id" : ObjectId("5c77bb562386c62d05142a79"), "UserId" : 2, "UserName" : "Carol Taylor" } { "_id" : ObjectId("5c77bb892386c62d05142a7c"), "UserId" : 5, "UserName" : "David Miller" } { "_id" : ObjectId("5c77bbb02386c62d05142a7d"), "UserId" : 6, "UserName" : "John Williams" }