在MongoDB数组中匹配元素?
您可以将$or运算符与limit(1)一起使用以匹配数组中的元素。首先让我们创建一个包含文档的集合-
> db.matchElementInArrayDemo.insertOne(
... {
... "StudentName" : "Chris" ,
... "StudentOtherDetails" :
... [
... {"StudentCountryName" : "US" , "StudentSkills" : "MongoDB"},
... {"StudentCountryName" : "UK" , "StudentSkills" : "Java"}
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd423282cba06f46efe9ee2")
}
> db.matchElementInArrayDemo.insertOne(
... {
... "StudentName" : "Chris" ,
... "StudentOtherDetails" :
... [
... {"StudentCountryName" : "AUS" , "StudentSkills" : "PHP"},
... {"StudentCountryName" : "US" , "StudentSkills" : "MongoDB"}
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd423412cba06f46efe9ee3")
}以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.matchElementInArrayDemo.find().pretty();
这将产生以下输出-
{
"_id" : ObjectId("5cd423282cba06f46efe9ee2"),
"StudentName" : "Chris",
"StudentOtherDetails" : [
{
"StudentCountryName" : "US",
"StudentSkills" : "MongoDB"
},
{
"StudentCountryName" : "UK",
"StudentSkills" : "Java"
}
]
}
{
"_id" : ObjectId("5cd423412cba06f46efe9ee3"),
"StudentName" : "Chris",
"StudentOtherDetails" : [
{
"StudentCountryName" : "AUS",
"StudentSkills" : "PHP"
},
{
"StudentCountryName" : "US",
"StudentSkills" : "MongoDB"
}
]
}这是匹配MongoDB数组中的元素的查询-
> db.matchElementInArrayDemo.find( { $or : [ {"StudentOtherDetails.StudentCountryName": "US" } ,{"StudentOtherDetails.StudentSkills": "MongoDB" } ] } ).limit(1);这将产生以下输出-
{ "_id" : ObjectId("5cd423282cba06f46efe9ee2"), "StudentName" : "Chris", "StudentOtherDetails" : [ { "StudentCountryName" : "US", "StudentSkills" : "MongoDB" }, { "StudentCountryName" : "UK", "StudentSkills" : "Java" } ] }热门推荐
10 18岁祝福语搞笑简短
11 周年蛋糕祝福语简短英语
12 祝福语写给自己的简短
13 最搞笑生日祝福语简短
14 送给老师中秋祝福语简短
15 发廊元旦祝福语大全简短
16 婚礼祝福语简短精辟的
17 对离岗同事祝福语简短
18 学校职工祝福语大全简短