问题描述
我的mongo数据库中有类似以下的数据.显然array1的长度是2,我正在寻找一种使用mongo db脚本来计算这种数组的长度的方法.谢谢
{"_id":ObjectId("65465465465465465468"),标题":{测试一下",},值":11.763548134011048,"array1":[{"q":{值":250}},{"q":{值":30,}}],"array2":[]}
您可以使用 $ size 聚合运算符.
鉴于您在OP中显示的文档,请使用以下命令...
db.collection.aggregate([{$ project:{sizeOfArray1:{$ size:"$ array1"}}}])
...将返回:
{"_id":ObjectId("65465465465465465468"),"sizeOfArray1":2}
此方法对Mongo> = 2.6
的所有版本均有效.
更新:针对此评论...
您可以使用带有.
的路径符号来寻址任何文档属性,以表示每个级别".因此,如果您的文档如下所示:
{"_id":ObjectId("65465465465465465468"),标题":{测试一下",数组":[1、2、3]},值":11.763548134011048,"array1":[{"q":{值":250}},{"q":{值":30,}}],"array2":[]}
...,则以下命令将返回 header
嵌套子文档中的 array
字段的计数:
db.collection.aggregate([{$ project:{sizeOfHeaderArray:{$ size:"$ header.array"}}}])
因此,也许现在您可以看到,您将使用 header.array
来解决 header
嵌套子文档中的 array
字段./p>
希望有帮助.
I have a data similar to the below in my mongo DB. Obviously the length of array1 is two and I am looking on a way to count the length of such array with mongo db script. Thanks
{
"_id" : ObjectId("65465465465465465468"),
"header" : {
"test" : "test",
},
"value" : 11.763548134011048,
"array1" : [
{
"q" : {
"value" : 250
}
},
{
"q" : {
"value" : 30,
}
}
],
"array2" : [ ]
}
You can use the $size aggregation operator.
Given the document you showed in your OP, the following command ...
db.collection.aggregate(
[
{
$project: {
sizeOfArray1: { $size: "$array1" }
}
}
]
)
... will return:
{
"_id" : ObjectId("65465465465465465468"),
"sizeOfArray1" : 2
}
This approach is valid for all versions of Mongo >= 2.6
.
Update: in response to this comment ...
You address any document attribute using path notation with a .
to denote each 'level'. So, if your document looked like this:
{
"_id" : ObjectId("65465465465465465468"),
"header" : {
"test" : "test",
"array" : [1, 2, 3]
},
"value" : 11.763548134011048,
"array1" : [
{
"q" : {
"value" : 250
}
},
{
"q" : {
"value" : 30,
}
}
],
"array2" : [ ]
}
... then the following command would return the count of the array
field inside the header
nested sub document:
db.collection.aggregate(
[
{
$project: {
sizeOfHeaderArray: { $size: "$header.array" }
}
}
]
)
So, perhaps you can now see that you would address the array
field inside the header
nested sub document using header.array
.
Hope that helps.
这篇关于mongoDB子元素上的数组长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!