如何在MongoDB中选择仅包含特定字段的对象?
首先让我们创建一个包含文档的集合-
> db.arrayContainOnlySpecificFieldDemo.insertOne(... {
... "StudentName":"John",
... "StudentAge":21,
... "StudentTechnicalSubject":["C","Java","MongoDB"]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc4921dac184d684e3fa26a")
}
> db.arrayContainOnlySpecificFieldDemo.insertOne( { "StudentName":"Carol",
"StudentAge":23, "StudentTechnicalSubject":["MongoDB"] } );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc49237ac184d684e3fa26b")
}
在find()方法的帮助下显示集合中的所有文档。查询如下-
> db.arrayContainOnlySpecificFieldDemo.find().pretty();
这将产生以下输出-
{"_id" : ObjectId("5cc4921dac184d684e3fa26a"),
"StudentName" : "John",
"StudentAge" : 21,
"StudentTechnicalSubject" : [
"C",
"Java",
"MongoDB"
]
}
{
"_id" : ObjectId("5cc49237ac184d684e3fa26b"),
"StudentName" : "Carol",
"StudentAge" : 23,
"StudentTechnicalSubject" : [
"MongoDB"
]
}
以下是选择数组仅包含特定字段的对象的查询-
> db.arrayContainOnlySpecificFieldDemo.find({"StudentTechnicalSubject":["MongoDB"]}).pretty();
这将产生以下输出-
{"_id" : ObjectId("5cc49237ac184d684e3fa26b"),
"StudentName" : "Carol",
"StudentAge" : 23,
"StudentTechnicalSubject" : [
"MongoDB"
]
}
以上是 如何在MongoDB中选择仅包含特定字段的对象? 的全部内容, 来源链接: utcz.com/z/317069.html