如何解决MongoDB对象数组
我面临的问题如下:
我有一个MongoDB文档,其结构如下
library("shiny")
library("esquisse")
ui <- fluidPage(
tags$h2("Demo dragulaInput"),tags$br(),tags$style("
span.label-danger{
display: inline-block;
width: 75px;
height: 75px;
background-color: blue;
color: red;
font-size: 25px;
}
"),dragulaInput(
inputId = "dad",sourceLabel = "Old",targetsLabels = c("New"),choices = levels(iris[,"Species"]),width = "250px",height = "200px",status = "danger"
),verbatimTextOutput(outputId = "result")
)
server <- function(input,output,session) {
output$result <- renderPrint({
new_level <- input$dad$target$New
new_level_1 <- c(new_level,input$dad$source)
})
}
shinyApp(ui = ui,server = server)
,我必须计算有多少个对象具有Alpha值。 我尝试了以下两个查询,但是都只给我值1。
"name": "XYZ","array":[
{
"value": "Alpha"
},{
"value": "Beta"
},{
"value": "Alpha"
},]
解决方法
find
收集方法返回文档,而不是片段。
一些用于计数数组中元素出现次数的选项:
大多数语言都提供了一种方法来过滤/减少/计算数组中的元素,因此在客户端应该很简单。
MongoDB聚合框架提供了$reduce
,$filter
,$size
,$group
,$unwind
以及其他一些在这种情况下可能有用的运算符
使用$reduce
的一种可能的解决方案:
db.current_database.aggregate([
{$match: {"array.value": "Alpha"}},{$addFields:{
count: {
$reduce: {
input: "$array",initialValue: 0,in: {
$cond: {
if: {$eq: ["$$this.value","Alpha"]},then: {$sum: ["$$value",1]},else: "$$value"
}
}
}
}
}}
])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。