找到一个严格的文件,其中只包含一个具有固定长度的特定字段?\n


对于这一点,你可以使用 $where 运算符。我们首先创建一个带有文档的集合 −

>db.veryStrictDocumentDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Doe","StudentAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda4bcdb50a6c6dd317adb8")
}
> db.veryStrictDocumentDemo.insertOne({"StudentFirstName":"Larry"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda4bdbb50a6c6dd317adb9")
}
>db.veryStrictDocumentDemo.insertOne({"StudentFirstName":"David","StudentLastName":"Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda4becb50a6c6dd317adba")
}
> db.veryStrictDocumentDemo.insertOne({"StudentFirstName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda4bfbb50a6c6dd317adbb")
}
> db.veryStrictDocumentDemo.insertOne({"StudentFirstName":"Bob","StudentLastName":"Brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda4c6db50a6c6dd317adbc")
}

以下是借助 find() 方法显示带有集合的所有文档的查询 −

> db.veryStrictDocumentDemo.find();

这将产生以下输出 −

{ "_id" : ObjectId("5cda4bcdb50a6c6dd317adb8"), "StudentFirstName" : "John", "StudentLastName" : "Doe", "StudentAge" : 23 }
{ "_id" : ObjectId("5cda4bdbb50a6c6dd317adb9"), "StudentFirstName" : "Larry" }
{ "_id" : ObjectId("5cda4becb50a6c6dd317adba"), "StudentFirstName" : "David", "StudentLastName" : "Miller" }
{ "_id" : ObjectId("5cda4bfbb50a6c6dd317adbb"), "StudentFirstName" : "Chris" }
{ "_id" : ObjectId("5cda4c6db50a6c6dd317adbc"), "StudentFirstName" : "Bob", "StudentLastName" : "Brown" }

以下是获取具有固定长度的特定字段的查询 −

> db.veryStrictDocumentDemo.find({
   "StudentFirstName": { $exists: true },
   "StudentLastName": { $exists: true },
   $where: function() { return Object.keys(this).length === 4 }
});

这将产生以下输出 −

{ "_id" : ObjectId("5cda4bcdb50a6c6dd317adb8"), "StudentFirstName" : "John", "StudentLastName" : "Doe", "StudentAge" : 23 }

更新于: 30-Jul-2019

61 次浏览量

开启你的 职业生涯

通过完成课程取得认证

开始吧
广告