如何计算Mongodb集合中数组中对象的元素存在的文档数
How to count the number of documents in which an element of an object inside an array exists in a collection of Mongodb
我有一个名为 Cards
的 MongoDB
collection
,其中包含结构类似的文档,如下所示:
{
"_id" : ObjectId("mongoid"),
"userName": "Har109",
"array1" : [
{
"id" : "11",
"name" : "hello world",
}
{
"id" : "21",
"name" : "bye world",
}
],
"array2" : [
{
"id" : "1",
"name" : "titanic",
}
{
"id" : "2",
"name" : "avatar",
}
],
"array3" : [
{
"id" : "1",
"name" : "The Alchemist",
}
{
"id" : "2",
"name" : "What is Zero",
}
]
}
我需要查询:统计集合中匹配"array1.id"的文档数然后可以对所有其他数组执行此操作(例如 "array2.id", "array3.id")
MongoDB Compass
中这种查询的语法是什么?
我试过了:获取所有文档的管道 array1
[{$count: 'array1'}]
但是如何将 where array1.id = "11" 的条件添加到 mongodb compass 上的此管道,其中阶段是单独完成的。
Count the number of Documents in the collection that matches "array1.id"
要查找包含 array.id=x
的文档数量,您可以 运行:
db.collection.find({ "array1.id":"11" }).countDocuments()
或使用聚合
db.collection.aggregate([
{ $match:{"array1.id":"11"} },
{ count:"array1" }
])
算法自动遍历数组
如果键不存在,将找不到文档。
我有一个名为 Cards
的 MongoDB
collection
,其中包含结构类似的文档,如下所示:
{
"_id" : ObjectId("mongoid"),
"userName": "Har109",
"array1" : [
{
"id" : "11",
"name" : "hello world",
}
{
"id" : "21",
"name" : "bye world",
}
],
"array2" : [
{
"id" : "1",
"name" : "titanic",
}
{
"id" : "2",
"name" : "avatar",
}
],
"array3" : [
{
"id" : "1",
"name" : "The Alchemist",
}
{
"id" : "2",
"name" : "What is Zero",
}
]
}
我需要查询:统计集合中匹配"array1.id"的文档数然后可以对所有其他数组执行此操作(例如 "array2.id", "array3.id")
MongoDB Compass
中这种查询的语法是什么?
我试过了:获取所有文档的管道 array1
[{$count: 'array1'}]
但是如何将 where array1.id = "11" 的条件添加到 mongodb compass 上的此管道,其中阶段是单独完成的。
Count the number of Documents in the collection that matches "array1.id"
要查找包含 array.id=x
的文档数量,您可以 运行:
db.collection.find({ "array1.id":"11" }).countDocuments()
或使用聚合
db.collection.aggregate([
{ $match:{"array1.id":"11"} },
{ count:"array1" }
])
算法自动遍历数组
如果键不存在,将找不到文档。