如何在 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" ] }
广告