MongoDB查询匹配数组的文档,与元素顺序无关
为此,请在MongoDB中使用$all。MongoDB中的$all运算符选择文档,其中字段的值是包含所有指定元素的数组。
首先让我们创建一个包含文档的集合-
> 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" }
]
}
以上是 MongoDB查询匹配数组的文档,与元素顺序无关 的全部内容, 来源链接: utcz.com/z/316383.html