您可以将dot(。)表示法与数组索引一起使用,以获取从特定元素开始的记录。首先让我们创建一个包含文档的集合-
>db.arrayStartsWithElementDemo.insertOne({"PlayerName":"Chris","PlayerScore":[780,9000,456,789,987]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd29fed345990cee87fd889") } >db.arrayStartsWithElementDemo.insertOne({"PlayerName":"Robert","PlayerScore":[890,670,890,54646,42424]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd2a00c345990cee87fd88a") } >db.arrayStartsWithElementDemo.insertOne({"PlayerName":"David","PlayerScore":[909090,896555,3344433,78900]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd2a025345990cee87fd88b") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.arrayStartsWithElementDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd29fed345990cee87fd889"), "PlayerName" : "Chris", "PlayerScore" : [ 780, 9000, 456, 789, 987 ] } { "_id" : ObjectId("5cd2a00c345990cee87fd88a"), "PlayerName" : "Robert", "PlayerScore" : [ 890, 670, 890, 54646, 42424 ] } { "_id" : ObjectId("5cd2a025345990cee87fd88b"), "PlayerName" : "David", "PlayerScore" : [ 909090, 896555, 3344433, 78900 ] }
以下是获取以特定元素890和670开始的数组的查询-
> db.arrayStartsWithElementDemo.find({"PlayerScore.0" : 890, "PlayerScore.1" : 670}).pretty();
这将产生以下输出。这里,
{ "_id" : ObjectId("5cd2a00c345990cee87fd88a"), "PlayerName" : "Robert", "PlayerScore" : [ 890, 670, 890, 54646, 42424 ] }