MongoDB 中查询数组大小大于1的文档
在处理需要验证数组大小或查找大小大于或小于特定长度的元素的项目时,可能会使用 $size、$where、$exists 等 MongoDB 运算符。
下面讨论的方法可以帮助您解决数组长度或数组大小问题。
样本数据
假设我们有以下数据。 我们将使用此示例数据在 MongoDB 中查询具有特定数组大小的文档。
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "reds"], book: { author:`xyz`, price:50, location:[`india`, `USA`, `nepal`]} },
{ item: "notebook", qty: 50, tags: ["reds", "blank"], book: { author:`xyz`, price:50, location:[`india`, `usa`]} },
{ item: "paper", qty: 100, tags: ["reds", "blank", "plain"], book: { author:`xyz`, price:50, location:[]}},
{ item: "planner", qty: 75, tags: ["blank", "reds"], book: { author:`xyz`, price:50, location:[`india`]} },
{ item: "postcard", qty: 45, tags: ["blue"], book:{} }
]);
MongoDB中使用$size运算符查询数组大小大于1的文档
MongoDB中的数组运算符类包含了很多用于引用数组获取文档的运算符; $size 就是其中之一。 $size 运算符用于获取包含特定大小的数组字段的文档。
它仅适用于数组并接受数值作为参数。
以下是 $size 运算符的主要功能:
- 它首先将数组字段与用户给定的大小进行比较,然后继续。
- 它检索包含满足前面步骤的字段的文档。
语法:
{array-field: {$size: <length-of-array>}}
在这种情况下,数组字段是文档中所需字段的名称,数组长度是与长度匹配的任何数字。
下面分享了一些示例,以了解如何在 MongoDB 中使用 $size
运算符。
db.inventory.find({tags:{$size:1}})
输出:
db.inventory.find({books.location:{$size:1}}
输出:
MongoDB中使用$where运算符查询数组大小大于1的文档
要向查询系统提供包含 JavaScript 表达式或完整 JavaScript 函数的字符串,请使用 $where 运算符。 它允许更大的灵活性,但它需要数据库为集合中的每个文档执行 JavaScript 表达式或函数。
使用 this 或 obj 在 JavaScript 表达式或函数中引用记录。
语法:
{ $where: <string|JavaScript Code> }
下面给出了示例来说明 $where
运算符的工作原理。
db.inventory.find({tags:{$where:`this.tags.length == 1`}}
输出:
db.inventory.find({tags:{$where:`this.tags.length >= 1`}}
你不能在 $where
的帮助下检查这个
仅在顶级文档上使用 $where
查询运算符。 它不会在嵌套页面中运行。
MongoDB中使用点号查询数组大小大于1的文档
为了访问数组元素和嵌入式文档的字段,MongoDB 使用点表示法。
访问数组元素
要通过从零开始的索引位置指定或访问数组元素,请将数组名称与点 (.) 和从零开始的索引位置连接起来,然后将其括在引号中。
语法:
"<array>.<index>"
例如,考虑文档中的以下字段。
{
...
contribs: [ "Turing machine", "Turing test", "Turingery" ],
...
}
使用点符号“contribs.2”来标识 contribs.2 数组中的第三个成员。
db.inventory.find({tags.0:{$exists:true`}}
It will look for elements with at least one tag // array with a zero-based index.
db.invantory.find({book.location.1: {$exists:true}}
// It looks for all components in whose book. There are at least two elements to a place.
MongoDB中使用$expr(3.6+)查询数组大小大于1的文档
语法:
{ $expr: { <expression> } }
db.invantory.find({
$expr: {
$gt: [{ $size: { $ifNull: ["$tags", []] } }, 0]
}
})
db.invantory.find({
$expr: {
$gt: [{ $size: { $ifNull: ["$book.location", []] } }, 1]
}
})
// $ifNull: ["$book.location", []] this is used to avoid any error if book.location is null
在 MongoDB 中使用聚合 $facet 运算符查询数组大小大于 1 的文档
该运算符在单个阶段中处理同一组输入文档的大量聚合。 每个管道在输出文档中都有其字段,其中结果保存为文档数组。
$facet 阶段支持创建多方面聚合,这些聚合在单个聚合阶段内跨多个维度或方面表征数据。 多方面聚合提供多个过滤器和分类以帮助数据浏览和分析。
例如,零售商经常使用分面来根据产品价格、制造商、尺寸等创建过滤器来减少搜索结果。
输入文档仅发送到 $facet 步骤一次。 $facet 允许对同一组输入文档进行大量聚合,而无需多次检索它们。
语法:
{ $facet:
{
<outputField1>: [ <stage1>, <stage2>, ... ],
<outputField2>: [ <stage1>, <stage2>, ... ],
...
}
}
输入每个管道的输出字段的名称。
$facet 中的每个子管道都接收相同的输入文档集。 这些子流水线相互独立,各自产生的文档数组存储在输出文档的不同字段中。
在同一个 $facet 阶段,一个子流水线的输出不能用作另一个子流水线的输入。 在 $facet 之后添加额外的阶段,并在需要进一步聚合时指示所需子管道输出的字段名称 outputField>。
$facet 阶段的索引使用
即使其子管道使用 $match 或者如果 $facet 是管道中的初始步骤,$facet 阶段及其子管道也不能使用索引。 在执行期间,$facet 阶段始终执行 COLLSCAN。
考虑一个在线商店,其库存存储在以下艺术品集合中:
{ "_id" : 1, "title" : "The Pillars of Society", "artists" : "Grosz", "year" : 1926,
"price" : NumberDecimal("199.99"),
"tags" : [ "painting", "satire", "Expressionism", "caricature" ] }
{ "_id" : 2, "title" : "Melancholy III", "artists" : "Munch", "year" : 1902,
"price" : NumberDecimal("280.00"),
"tags" : [ "woodcut", "Expressionism" ] }
{ "_id" : 3, "title" : "Dancer", "artists" : "Miro", "year" : 1925,
"price" : NumberDecimal("76.04"),
"tags" : [ "oil", "Surrealism", "painting" ] }
{ "_id" : 4, "title" : "The Great Wave off Kanagawa", "artists" : "Hokusai",
"price" : NumberDecimal("167.30"),
"tags" : [ "woodblock", "ukiyo-e" ] }
{ "_id" : 5, "title" : "The Persistence of Memory", "artist" : "Dali", "year" : 1931,
"price" : NumberDecimal("483.00"),
"tags" : [ "Surrealism", "painting", "oil" ] }
{ "_id" : 6, "title" : "Composition VII", "artist" : "Kandinsky", "year" : 1913,
"price" : NumberDecimal("385.00"),
"tags" : [ "oil", "painting", "abstract" ] }
{ "_id" : 7, "title" : "The Scream", "artist" : "Munch", "year" : 1893,
"tags" : [ "Expressionism", "painting", "oil" ] }
{ "_id" : 8, "title" : "Blue Flower", "artist" : "O`Keefe", "year" : 1918,
"price" : NumberDecimal("118.42"),
"tags" : [ "abstract", "painting" ] }
以下过程利用 MongoDB 的分面功能向消费者展示按标签、价格和生成年份组织的商店库存。 这个 $facet 阶段包含三个子管道,它们使用 $sortByCount、$bucket 或 $bucketAuto 执行此多方面聚合。
来自艺术品的输入文档仅在操作开始时从数据库中检索一次。
例子:
db.artwork.aggregate( [
{
$facet: {
"categorizedByTags": [
{ $unwind: "$tags" },
{ $sortByCount: "$tags" }
],
"categorizedByPrice": [
// Filter out documents without a price e.g., _id: 7
{ $match: { price: { $exists: 1 } } },
{
$bucket: {
groupBy: "$price",
boundaries: [ 0, 150, 200, 300, 400 ],
default: "Other",
output: {
"count": { $sum: 1 },
"titles": { $push: "$title" }
}
}
}
],
"categorizedByYears(Auto)": [
{
$bucketAuto: {
groupBy: "$year",
buckets: 4
}
}
]
}
}
])
输出:
相关文章
在 MongoDB Shell 中列出所有数据库
发布时间:2023/05/11 浏览次数:180 分类:MongoDB
-
交互式 Mongo Shell 提供了多个用于获取数据的选项。 本文介绍了在 Mongo Shell 中列出数据库的几种不同方法。
MongoDB 中检查字段包含的字符串
发布时间:2023/05/11 浏览次数:1024 分类:MongoDB
-
这篇文章解决了如何在 MongoDB 中使用正则表达式来确定字段是否包含字符串。在 MongoDB 中使用正则表达式 正则表达式 (regex) 是定义搜索模式的文本字符串。
在 MongoDB 中 upsert 更新插入
发布时间:2023/05/11 浏览次数:214 分类:MongoDB
-
在 MongoDB 中,upsert 结合了更新和插入命令。 它可以在 update() 和 findAndModify() 操作中使用。MongoDB 中的 upsert 查询 upsert 采用单个布尔参数。
如何卸载 MongoDB
发布时间:2023/05/11 浏览次数:745 分类:MongoDB
-
要从您的计算机中卸载 MongoDB,您必须先删除 MongoDB 服务、数据库和日志文件。使用这篇 MongoDB 文章,您将能够从 Ubuntu Linux、Mac 和 Windows 卸载 MongoDB。 请务必保留数据备份,因为一旦卸载,便
在 MongoDB 中存储日期和时间
发布时间:2023/05/11 浏览次数:762 分类:MongoDB
-
本 MongoDB 教程解释了 Date() 对象是什么以及如何使用 Date() 方法对集合进行排序。 这也将帮助您找到在 MongoDB 中显示和存储日期/时间的最佳方法。
MongoDB 按 ID 查找
发布时间:2023/05/11 浏览次数:1856 分类:MongoDB
-
MongoDB 中的 find by Id() 函数用于获取与用户提供的 id 相匹配的文档。 如果找不到与指定 ID 匹配的文档,则返回空值。
检查 MongoDB 服务器是否正在运行
发布时间:2023/05/11 浏览次数:247 分类:MongoDB
-
这篇 MongoDB 教程将告诉您如何检查是否安装了 MongoDB 以及安装的 MongoDB 服务器的版本。 它在 Windows、UBUNTU 和 MAC 等不同的操作系统中实现。
MongoDB 中的分页
发布时间:2023/05/11 浏览次数:174 分类:MongoDB
-
这篇文章将介绍什么是 MongoDB 中的分页。 为什么在 MongoDB 中需要分页以及在 MongoDB 中完成分页的不同方法或方式是什么。
MongoDB 从查询开始
发布时间:2023/05/11 浏览次数:186 分类:MongoDB
-
在这篇 MongoDB 文章中,用户将学习如何使用 $regex 进行开始查询。 它为查询中的模式匹配字符串提供正则表达式功能。