在使用$ size opration的例子中,作者狡猾地避免使用空格:
{ "_id" : 1, "item" : "ABC1", "description" : "product 1", colors: [ "blue", "black", "red" ] }
{ "_id" : 2, "item" : "ABC2", "description" : "product 2", colors: [ "purple" ] }
{ "_id" : 3, "item" : "XYZ1", "description" : "product 3", colors: [ ] }
请注意,所有字段都是引号,只有巧合的颜色不是:)
但如果我们有:
{ "_id" : 1, "item" : "ABC1", "description" : "product 1", "true colors": [ "blue", "black", "red" ] }
{ "_id" : 2, "item" : "ABC2", "description" : "product 2", "true colors": [ "purple" ] }
{ "_id" : 3, "item" : "XYZ1", "description" : "product 3", "true colors": [ ] }
我们如何编写查询:
numberOfColors: { $size: "$colors" }
更新
我找到了
numberOfColors: { $size: "$true colors" }
正常工作。但是"点符号&#34 ;?我如何在这些字段中引用嵌套对象?
答案 0 :(得分:0)
正如Alex在评论中提到的那样,给出了如下文档的嵌套对象
{ "_id" : 1, "item" : "ABC1", "description" : "product 1",
"all colors" : { "true colors" : [ "blue", "black", "red" ] } }
{ "_id" : 2, "item" : "ABC2", "description" : "product 2",
"all colors" : { "true colors" : [ "purple" ] } }
查询可能是
db.sp.aggregate([
{$project: {item: 1, numberOfColor: {$size: '$all colors.true colors'}}}
]);
结果是
{ "_id" : 1, "item" : "ABC1", "numberOfColor" : 3 }
{ "_id" : 2, "item" : "ABC2", "numberOfColor" : 1 }