从 MongoDB 中与条件匹配的多个子文档中获取字段?
若要从多个子文档获取字段,请结合 $ unwind 使用 MongoDB aggregate。让我们创建一个包含文档的集合——
> 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" }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP