查询嵌套的mongo文档

时间:2016-06-17 07:20:32

标签: mongodb mongodb-query

我在MongoDB中存储的JSON文档很少,基本上是错误报告,即每个文档都包含数据集之间的嵌套数据结构不匹配。它们如下所示:

library(shiny)
library(DT)
mymtcars = mtcars
mymtcars$id = 1:nrow(mtcars)
runApp(
  list(ui = pageWithSidebar(
    headerPanel('Examples of DataTables'),
    sidebarPanel(
      checkboxGroupInput('show_vars', 'Columns to show:', names(mymtcars),
                         selected = names(mymtcars))
      ,textInput("collection_txt",label="Foo")
    ),
    mainPanel(
      DT::dataTableOutput("mytable")
    )
  )
  , server = function(input, output, session) {

    shinyInput <- function(FUN,id,num,...) {
      inputs <- character(num)
      for (i in seq_len(num)) {
        inputs[i] <- as.character(FUN(paste0(id,i),label=NULL,...))
      }
      inputs
    }

    rowSelect <- reactive({

      rows=names(input)[grepl(pattern = "srows_",names(input))]
      paste(unlist(lapply(rows,function(i){
        if(input[[i]]==T){
          return(substr(i,gregexpr(pattern = "_",i)[[1]]+1,nchar(i)))
        }
      })))

    })

    observe({
      updateTextInput(session, "collection_txt", value = rowSelect() ,label = "Foo:" )
    })
    output$mytable = DT::renderDataTable({
      #Display table with checkbox buttons
    DT::datatable(cbind(Pick=shinyInput(checkboxInput,"srows_",nrow(mymtcars),value=NULL,width=1), mymtcars[, input$show_vars, drop=FALSE]),
                    options = list(orderClasses = TRUE,
                                   lengthMenu = c(5, 25, 50),
                                   pageLength = 25 ,

                                   drawCallback= JS(
                                     'function(settings) {
                                     Shiny.bindAll(this.api().table().node());}')
                                  ),selection='none',escape=F)


      } 
  )


    })
                    )

因此,在上述情况下,流程/工具会确定 { "nodename": "BLAH" "errors": { "PC": { "value": { "PC93196": [ "post", "casper" ], "PC03196": [ "netdb" ] } } } } PC的{​​{1}}值。在这种情况下,PC93196报告的PC值与PC03196netdb的值不同。

如何查询涉及流程/工具post的所有错误文档?

1 个答案:

答案 0 :(得分:0)

文档架构并不适合以您尝试的方式轻松查询。这是因为value对象由命名对象组成,而不是对象数组。即value对象有两个属性:PC93196PC03196

如果您的文档结构略有不同,那么以您想要的方式查询会更容易。例如,像这样的文档结构:

{
  "nodename": "BLAH",
  "errors": {
    "PC": [
      {
        "name": "PC93196",
        "type": [
          "post",
          "casper"
        ]
      },
      {
        "name": "PC03196",
        "type": [
          "netdb"
        ]
      }
    ]
  }
}

允许您编写如下查询:

db.errors.aggregate([{$unwind:"$errors.PC"},{$match:{"errors.PC.type":"casper"}}])

会提供结果:

{ "_id" : ObjectId("5763c480dad14fd061657f91"), "nodename" : "BLAH", "errors" : { "PC" : { "name" : "PC93196", "type" : [ "post", "casper" ] } } }