查找仅包含固定长度特定字段的严格文档?
您可以为此使用$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 }
以上是 查找仅包含固定长度特定字段的严格文档? 的全部内容, 来源链接: utcz.com/z/326534.html