要查询数组内部并检查是否存在以获取计数,请使用$exists。让我们创建一个包含文档的集合-
> db.demo296.insertOne( ... { ... "id":101, ... "Name":"Chris", ... "details":[ ... { ... SubjectId:[101,103], ... "SubjectName":["MySQL","MongoDB"] ... }, ... { ... SubjectId:[102,104], ... "SubjectName":["Java","C"] ... } ... ] ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5e4d51715d93261e4bc9ea3b") } > db.demo296.insertOne( ...{ ... "id":102, ... "Name":"David", ... "details":[ ... { ... SubjectId:[110,113] ... ... }, ... { ... SubjectId:[112,114] ... ... } ... ] ...} ...); { "acknowledged" : true, "insertedId" : ObjectId("5e4d519b5d93261e4bc9ea3c") } > db.demo296.insertOne( ... { ... "id":103, ... "Name":"Bob", ... "details":[ ... { ... "SubjectName":["C++","Python"] ... }, ... { ... "SubjectName":["Spring","Hibernate"] ... } ... ] ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5e4d52315d93261e4bc9ea3d") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo296.find();
这将产生以下输出-
{ "_id" : ObjectId("5e4d51715d93261e4bc9ea3b"), "id" : 101, "Name" : "Chris", "details" : [ { "SubjectId" : [ 101, 103 ], "SubjectName" : [ "MySQL", "MongoDB" ] }, { "SubjectId" : [ 102, 104 ], "SubjectName" : [ "Java", "C" ] } ] } { "_id" : ObjectId("5e4d519b5d93261e4bc9ea3c"), "id" : 102, "Name" : "David", "details" : [ { "SubjectId" : [ 110, 113 ] }, { "SubjectId" : [ 112, 114 ] } ] } { "_id" : ObjectId("5e4d52315d93261e4bc9ea3d"), "id" : 103, "Name" : "Bob", "details" : [ { "SubjectName" : [ "C++", "Python" ] }, { "SubjectName" : [ "Spring", "Hibernate" ] } ] }
以下是如何在数组内查询MongoDB并获取计数-
> db.demo296.count( { 'details.SubjectName': {$exists: true }} );
这将产生以下输出-
2