使用MongoDB搜索与数组中的第一项匹配的文档吗?
首先让我们创建一个包含文档的集合-
> db.matchingFirstItemInTheArrayDemo.insertOne( { "ClientDetails": [ { "ClientName": "Larry", "ClientAge":28 } ] } ); { "acknowledged" : true, "insertedId" : ObjectId("5cd7a5d26d78f205348bc636") } > db.matchingFirstItemInTheArrayDemo.insertOne( { "ClientDetails": [ { "ClientName": "Chris", "ClientAge":56, } ] } ); { "acknowledged" : true, "insertedId" : ObjectId("5cd7a5f56d78f205348bc637") } > db.matchingFirstItemInTheArrayDemo.insertOne( { "ClientDetails": [ { "ClientName": "Robert", "ClientAge":46, } ] } ); { "acknowledged" : true, "insertedId" : ObjectId("5cd7a6076d78f205348bc638") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.matchingFirstItemInTheArrayDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd7a5d26d78f205348bc636"), "ClientDetails" : [ { "ClientName" : "Larry", "ClientAge" : 28 } ] } { "_id" : ObjectId("5cd7a5f56d78f205348bc637"), "ClientDetails" : [ { "ClientName" : "Chris", "ClientAge" : 56 } ] } { "_id" : ObjectId("5cd7a6076d78f205348bc638"), "ClientDetails" : [ { "ClientName" : "Robert", "ClientAge" : 46 } ] }
以下是搜索匹配数组中第一项的文档的查询-
> db.matchingFirstItemInTheArrayDemo.find({"ClientDetails.0.ClientName":"Chris"});
这将产生以下输出-
{ "_id" : ObjectId("5cd7a5f56d78f205348bc637"), "ClientDetails" : [ { "ClientName" : "Chris", "ClientAge" : 56 } ] }