在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" } }
以上是 在MongoDB中执行嵌套文档值搜索? 的全部内容, 来源链接: utcz.com/z/331382.html