如何在 MongoDB 中获取符合条件的多个子文档的字段?
mongodbdatabasebig data analytics更新于 2026/1/6 16:52:17
要获取多个子文档的字段,请使用 MongoDB 的 $unwind 聚合函数。让我们创建一个包含文档的集合 −
> db.demo671.insertOne(
... {
...
... "details" : [
... {
... "id" : "1"
... },
... {
... CountryName:"US",
... "details1" : [
... {
... "id" : "1"
... },
... {
... "id" : "2"
... }
... ]
... },
... {
... CountryName:"UK",
... "details1" : [
... {
... "id" : "2"
... },
... {
... "id" : "1"
... }
... ]
... },
... {
... CountryName:"AUS",
... "details1" : [
... {
... "id" : "1"
... }
... ]
... }
... ]
... }
... )
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea3e5d004263e90dac943e0")
}
借助 find() 方法显示集合中的所有文档 −
> db.demo671.find();
这将产生以下输出 −
{ "_id" : ObjectId("5ea3e5d004263e90dac943e0"), "details" : [ { "id" : "1" }, { "CountryName" : "US", "details1" : [ { "id" : "1" }, { "id" : "2" } ] }, { "CountryName" : "UK", "details1" : [ { "id" : "2" }, { "id" : "1" } ] }, { "CountryName" : "AUS", "details1" : [ { "id" : "1" } ] } ] }
这是从 MongoDB 中符合条件的多个子文档中获取字段的查询 −
> db.demo671.aggregate([
...
... {$unwind: '$details'},
...
... {$match: {'details.details1.id': '1'}},
...
... {$project: {_id: 0, Country: '$details.CountryName'}}
... ]).pretty()
这将产生以下输出 −
{ "Country" : "US" }
{ "Country" : "UK" }
{ "Country" : "AUS" }

