在 MongoDB 中查詢大於特定長度的字串?


要在 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"
}

更新於: 30-Jul-2019

2K+ 瀏覽量

開啟您的職業

完成課程獲得認證

開始
廣告