在 MongoDB 中执行嵌套文档值搜索?
为了搜索值,在 MongoDB 中使用 $match。让我们创建一个带有文档的集合 −
> db.demo648.insertOne( ... { ... StudentInformation: ... [ ... { ... Name:"John", ... CountryName:"US" ... }, ... { ... Name:"David", ... CountryName:"AUS" ... }, ... { ... Name:"Chris", ... CountryName:"US" ... }, ... { ... Name:"Robert", ... CountryName:"UK" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e9c8b286c954c74be91e6f5") }
在集合中显示所有文档,使用 find() 方法 −
> db.demo648.find();
这将生成以下输出 −
{ "_id" : ObjectId("5e9c8b286c954c74be91e6f5"), "StudentInformation" : [ { "Name" : "John", "CountryName" : "US" }, { "Name" : "David", "CountryName" : "AUS" }, { "Name" : "Chris", "CountryName" : "US" }, { "Name" : "Robert", "CountryName" : "UK" } ] }
以下是 MongoDB 中搜索值的查询 −
> db.demo648.aggregate([ ... { $unwind: "$StudentInformation" }, ... { $match: { "StudentInformation.CountryName": "US" } }, ... { $project: {_id: 0}} ... ])
这将生成以下输出 −
{ "StudentInformation" : { "Name" : "John", "CountryName" : "US" } } { "StudentInformation" : { "Name" : "Chris", "CountryName" : "US" } }
广告