您可以为此使用$where运算符。首先让我们创建一个包含文档的集合-
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"John","StudentScores":[45,78,89,90]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd2a219345990cee87fd88c") } >db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"Larry","StudentScores":[45,43,34,33]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd2a22a345990cee87fd88d") } >db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"Chris","StudentScores":[]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd2a23c345990cee87fd88e") } >db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"David","StudentScores":[99]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd2a24d345990cee87fd88f") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.searchDocumentArrayIntegerDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd2a219345990cee87fd88c"), "StudentFirstName" : "John", "StudentScores" : [ 45, 78, 89, 90 ] } { "_id" : ObjectId("5cd2a22a345990cee87fd88d"), "StudentFirstName" : "Larry", "StudentScores" : [ 45, 43, 34, 33 ] } { "_id" : ObjectId("5cd2a23c345990cee87fd88e"), "StudentFirstName" : "Chris", "StudentScores" : [ ] } { "_id" : ObjectId("5cd2a24d345990cee87fd88f"), "StudentFirstName" : "David", "StudentScores" : [ 99 ] }
情况1-查询数组何时包含至少一个值-
> db.searchDocumentArrayIntegerDemo.find({ $where: "this.StudentScores.length >= 1" } );
这将产生以下输出-
{ "_id" : ObjectId("5cd2a219345990cee87fd88c"), "StudentFirstName" : "John", "StudentScores" : [ 45, 78, 89, 90 ] } { "_id" : ObjectId("5cd2a22a345990cee87fd88d"), "StudentFirstName" : "Larry", "StudentScores" : [ 45, 43, 34, 33 ] } { "_id" : ObjectId("5cd2a24d345990cee87fd88f"), "StudentFirstName" : "David", "StudentScores" : [ 99 ] }
情况2-查询数组在所有文档中是否包含一个公共值-
> db.searchDocumentArrayIntegerDemo.find({StudentScores: 45}, {StudentScores:1});
这将产生以下输出-
{ "_id" : ObjectId("5cd2a219345990cee87fd88c"), "StudentScores" : [ 45, 78, 89, 90 ] } { "_id" : ObjectId("5cd2a22a345990cee87fd88d"), "StudentScores" : [ 45, 43, 34, 33 ] }