用MongoDB查询数组元素?
查询数组元素时,MongoDB更好。让我们使用以下语法查询数组元素-
db.yourCollectionName.find({yourArrayFieldName:"yourValue"}).pretty();
上面的语法将返回所有在数组字段中具有“ yourValue”值的文档。
为了理解这个概念,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.queryArrayElementsDemo.insertOne({... "StudentName":"John","StudentFavouriteSubject":["C","Java"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90c0354afe5c1d2279d694")
}
> db.queryArrayElementsDemo.insertOne({ "StudentName":"Carol","StudentFavouriteSubject":["C","C++"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90c0434afe5c1d2279d695")
}
> db.queryArrayElementsDemo.insertOne({ "StudentName":"David","StudentFavouriteSubject":["MongoDB","Java"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90c0584afe5c1d2279d696")
}
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.queryArrayElementsDemo.find().pretty();
以下是输出-
{"_id" : ObjectId("5c90c0354afe5c1d2279d694"),
"StudentName" : "John",
"StudentFavouriteSubject" : [
"C",
"Java"
]
}
{
"_id" : ObjectId("5c90c0434afe5c1d2279d695"),
"StudentName" : "Carol",
"StudentFavouriteSubject" : [
"C",
"C++"
]
}
{
"_id" : ObjectId("5c90c0584afe5c1d2279d696"),
"StudentName" : "David",
"StudentFavouriteSubject" : [
"MongoDB",
"Java"
]
}
使用MongoDB查询数组元素-
> db.queryArrayElementsDemo.find({StudentFavouriteSubject:"Java"}).pretty();
以下是输出-
{"_id" : ObjectId("5c90c0354afe5c1d2279d694"),
"StudentName" : "John",
"StudentFavouriteSubject" : [
"C",
"Java"
]
}
{
"_id" : ObjectId("5c90c0584afe5c1d2279d696"),
"StudentName" : "David",
"StudentFavouriteSubject" : [
"MongoDB",
"Java"
]
}
查看上面的示例输出,上面的查询返回所有带有“ Java”值的文档。
以上是 用MongoDB查询数组元素? 的全部内容, 来源链接: utcz.com/z/348955.html