如何在 MongoDB 中检索值以特定字符结尾的文档?


以下是 MongoDB 中检索值以特定字符结尾的文档的语法

db.yourCollectionName.find({yourFieldName: {$regex: "yourEndingCharacter$"}}).pretty();

我们首先使用文档创建一个集合

>db.retrieveDocumentsWithEndsWithParticularCharacterDemo.insertOne({"StudentName":"Adam","StudentAge":25,"StudentCountryName":"LAOS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9c45b32d66697741252456")
}
>db.retrieveDocumentsWithEndsWithParticularCharacterDemo.insertOne({"StudentName":"Sam","StudentAge":24,"StudentCountryName":"ANGOLA"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9c45c02d66697741252457")
}
>db.retrieveDocumentsWithEndsWithParticularCharacterDemo.insertOne({"StudentName":"Robert","StudentAge":21,"StudentCountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9c45cb2d66697741252458")
}
>db.retrieveDocumentsWithEndsWithParticularCharacterDemo.insertOne({"StudentName":"Chris","StudentAge":20,"StudentCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9c45d92d66697741252459")
}
>db.retrieveDocumentsWithEndsWithParticularCharacterDemo.insertOne({"StudentName":"Larry","StudentAge":23,"StudentCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9c45eb2d6669774125245a")
}

以下是使用 find() 方法显示集合中所有文档的查询

> db.retrieveDocumentsWithEndsWithParticularCharacterDemo.find().pretty();

这将产生以下输出

{
   "_id" : ObjectId("5c9c45b32d66697741252456"),
   "StudentName" : "Adam",
   "StudentAge" : 25,
   "StudentCountryName" : "LAOS"
}
{
   "_id" : ObjectId("5c9c45c02d66697741252457"),
   "StudentName" : "Sam",
   "StudentAge" : 24,
   "StudentCountryName" : "ANGOLA"
}
{
   "_id" : ObjectId("5c9c45cb2d66697741252458"),
   "StudentName" : "Robert",
   "StudentAge" : 21,
   "StudentCountryName" : "AUS"
}
{
   "_id" : ObjectId("5c9c45d92d66697741252459"),
   "StudentName" : "Chris",
   "StudentAge" : 20,
   "StudentCountryName" : "UK"
}
{
   "_id" : ObjectId("5c9c45eb2d6669774125245a"),
   "StudentName" : "Larry",
   "StudentAge" : 23,
   "StudentCountryName" : "US"
}

以下是检索 MongoDB 中值以特定字符结尾的文档的查询。我们正在检查以字符“S”结尾的值

> db.retrieveDocumentsWithEndsWithParticularCharacterDemo.find({StudentCountryName: {$regex: "S$"}}).pretty();

这将产生以下输出

{
   "_id" : ObjectId("5c9c45b32d66697741252456"),
   "StudentName" : "Adam",
   "StudentAge" : 25,
   "StudentCountryName" : "LAOS"
}
{
   "_id" : ObjectId("5c9c45cb2d66697741252458"),
   "StudentName" : "Robert",
   "StudentAge" : 21,
   "StudentCountryName" : "AUS"
}
{
   "_id" : ObjectId("5c9c45eb2d6669774125245a"),
   "StudentName" : "Larry",
   "StudentAge" : 23,
   "StudentCountryName" : "US"
}

更新于: 30-7-2019

1K+ 浏览

职业生涯起步

通过完成该课程获得认证

开始
广告