mongoDB子元素上的数组长度 [英] mongoDB Array length on children element
问题描述
我的mongo数据库中有类似以下的数据.显然array1的长度是2,我正在寻找一种使用mongo db脚本来计算这种数组的长度的方法.谢谢
{"_id":ObjectId("65465465465465465468"),标题":{测试一下",},值":11.763548134011048,"array1":[{"q":{值":250}},{"q":{值":30,}}],"array2":[]}
您可以使用 ...将返回: 此方法对Mongo> = 更新:针对此评论... 如果在到达数组之前有更多的嵌套对象,则可以使用相同的代码,而只是将字段名称更改为我感兴趣的项目? 您可以使用带有 ...,则以下命令将返回 因此,也许现在您可以看到,您将使用 希望有帮助. 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
You can use the $size aggregation operator. Given the document you showed in your OP, the following command ... ... will return: This approach is valid for all versions of Mongo >= Update: in response to this comment ... If I have more nested objects until I reach to my array I can use they same code and I just change the name of the field to the item that I am interested in? You address any document attribute using path notation with a ... then the following command would return the count of the So, perhaps you can now see that you would address the Hope that helps. 这篇关于mongoDB子元素上的数组长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
{"_id":ObjectId("65465465465465465468"),"sizeOfArray1":2}
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>{
"_id" : ObjectId("65465465465465465468"),
"header" : {
"test" : "test",
},
"value" : 11.763548134011048,
"array1" : [
{
"q" : {
"value" : 250
}
},
{
"q" : {
"value" : 30,
}
}
],
"array2" : [ ]
}
db.collection.aggregate(
[
{
$project: {
sizeOfArray1: { $size: "$array1" }
}
}
]
)
{
"_id" : ObjectId("65465465465465465468"),
"sizeOfArray1" : 2
}
2.6
.
.
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" : [ ]
}
array
field inside the header
nested sub document:db.collection.aggregate(
[
{
$project: {
sizeOfHeaderArray: { $size: "$header.array" }
}
}
]
)
array
field inside the header
nested sub document using header.array
.