如何在 MongoDB 中通过整数数组搜索文档?
对此,您可以使用 $where 运算符。我们首先使用文档创建一个集合 -
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"John","StudentScores":[45,78,89,90]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a219345990cee87fd88c")
}
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"Larry","StudentScores":[45,43,34,33]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a22a345990cee87fd88d")
}
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"Chris","StudentScores":[]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a23c345990cee87fd88e")
}
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"David","StudentScores":[99]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a24d345990cee87fd88f")
}以下是对集合中所有文档显示查询,采用 find() 方法 -
> db.searchDocumentArrayIntegerDemo.find().pretty();
将会产生以下输出 -
{
"_id" : ObjectId("5cd2a219345990cee87fd88c"),
"StudentFirstName" : "John",
"StudentScores" : [
45,
78,
89,
90
]
}
{
"_id" : ObjectId("5cd2a22a345990cee87fd88d"),
"StudentFirstName" : "Larry",
"StudentScores" : [
45,
43,
34,
33
]
}
{
"_id" : ObjectId("5cd2a23c345990cee87fd88e"),
"StudentFirstName" : "Chris",
"StudentScores" : [ ]
}
{
"_id" : ObjectId("5cd2a24d345990cee87fd88f"),
"StudentFirstName" : "David",
"StudentScores" : [
99
]
}情况 1 - 数组中包含至少一个值时的查询 -
> db.searchDocumentArrayIntegerDemo.find({ $where: "this.StudentScores.length >= 1" } );将会产生以下输出 -
{ "_id" : ObjectId("5cd2a219345990cee87fd88c"), "StudentFirstName" : "John", "StudentScores" : [ 45, 78, 89, 90 ] }
{ "_id" : ObjectId("5cd2a22a345990cee87fd88d"), "StudentFirstName" : "Larry", "StudentScores" : [ 45, 43, 34, 33 ] }
{ "_id" : ObjectId("5cd2a24d345990cee87fd88f"), "StudentFirstName" : "David", "StudentScores" : [ 99 ] }情况 2 - 数组中包含所有文档中的一个通用值时的查询 -
> db.searchDocumentArrayIntegerDemo.find({StudentScores: 45}, {StudentScores:1});将会产生以下输出 -
{ "_id" : ObjectId("5cd2a219345990cee87fd88c"), "StudentScores" : [ 45, 78, 89, 90 ] }
{ "_id" : ObjectId("5cd2a22a345990cee87fd88d"), "StudentScores" : [ 45, 43, 34, 33 ] }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP