查询匹配数组的 MongoDB 文档,不考虑元素的顺序
为此,在 MongoDB 中使用 $all。MongoDB 中的 $all 运算符选择 value 为 array 的文档,其中包含所有指定的元素。
我们首先使用文档创建集合 -
> db.demo370.insertOne( ... { ... "Name" : "Chris", ... "details" : [ ... { ... "Subject" : "MySQL", ... "CountryName" : "US" ... }, ... { ... "Subject" : "MongoDB", ... "CountryName" : "UK" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e57e9892ae06a1609a00af0") } > db.demo370.insertOne( ... { ... "Name" : "David", ... "details" : [ ... { "Subject" : "Java", ... "CountryName" : "AUS" ... }, ... { ... "Subject" : "Spring", ... "CountryName" : "UK" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e57e9972ae06a1609a00af1") }
使用 find() 方法显示集合中的所有文档 -
> db.demo370.find();
这将产生以下输出 -
{ "_id" : ObjectId("5e57e9892ae06a1609a00af0"), "Name" : "Chris", "details" : [ { "Subject" : "MySQL", "CountryName" : "US" }, { "Subject" : "MongoDB", "CountryName" : "UK" } ] } { "_id" : ObjectId("5e57e9972ae06a1609a00af1"), "Name" : "David", "details" : [ { "Subject" : "Java", "CountryName" : "AUS" }, { "Subject" : "Spring", "CountryName" : "UK" } ] }
以下是查询匹配数组的文档,不考虑元素顺序 -
> db.demo370.find({ ... details: {$all: [ ... {Subject:"MySQL","CountryName" : "US"}, ... {Subject:"MongoDB", "CountryName" : "UK"} ... ]}})
这将产生以下输出 -
{ "_id" : ObjectId("5e57e9892ae06a1609a00af0"), "Name" : "Chris", "details" : [ { "Subject" : "MySQL", "CountryName" : "US" }, { "Subject" : "MongoDB", "CountryName" : "UK" } ] }
广告