要使用长度条件查询MongoDB,可以使用正则表达式。以下是语法
db.yourCollectionName.find({ ‘yourFieldName’: { $regex: /^.{yourLengthValue1,yourLengthValue2}$/ } });
让我们创建包含文档的集合。以下是查询
> db.queryLengthDemo.insertOne({"StudentFullName":"John Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9a01ae353decbc2fc927c0") } > db.queryLengthDemo.insertOne({"StudentFullName":"John Doe"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9a01b4353decbc2fc927c1") } > db.queryLengthDemo.insertOne({"StudentFullName":"David Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9a01c2353decbc2fc927c2") } > db.queryLengthDemo.insertOne({"StudentFullName":"Robert Taylor"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9a01e2353decbc2fc927c3") } > db.queryLengthDemo.insertOne({"StudentFullName":"Chris Williams"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9a01f1353decbc2fc927c4") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.queryLengthDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9a01ae353decbc2fc927c0"), "StudentFullName" : "John Smith" } { "_id" : ObjectId("5c9a01b4353decbc2fc927c1"), "StudentFullName" : "John Doe" } { "_id" : ObjectId("5c9a01c2353decbc2fc927c2"), "StudentFullName" : "David Miller" } { "_id" : ObjectId("5c9a01e2353decbc2fc927c3"), "StudentFullName" : "Robert Taylor" } { "_id" : ObjectId("5c9a01f1353decbc2fc927c4"), "StudentFullName" : "Chris Williams" }
以下是MongoDB中具有长度条件的查询
> db.queryLengthDemo.find({ StudentFullName: { $regex: /^.{9,12}$/ } }).pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9a01ae353decbc2fc927c0"), "StudentFullName" : "John Smith" } { "_id" : ObjectId("5c9a01c2353decbc2fc927c2"), "StudentFullName" : "David Miller" }