首页 > 解决方案 > Shiny R 中的 Mongodb Query 使用响应式输入从数据库中获取数据

问题描述

library(shiny)
library(mongolite)

ui <- fluidPage( 
    titlePanel("Mongodb Data"),
    sidebarLayout(
        sidebarPanel(
             textInput("_id", "Document type:", "")
        ),
        mainPanel(
            dataTableOutput("mydata")
        )
    )
)

server <- function(input, output) {
    mon <- mongo(collection = "collectionname", db = "db name", url = "mongodb://localhost:27017")
    output$mydata <- renderDataTable({
        doc_type <- paste0(doc_type= input$doc_id)

        mon$find(  query = '{"doc_type" : {"$in" : ["x", "y"]} }' , limit = 100) 
    })
}
}

警告:错误,如果没有活动的反应上下文,则不允许操作。(你试图做一些只能从反应式表达式或观察者内部完成的事情。)

如何添加响应式查询并从 MongoDB 集合中的特定列检索数据?每当我给文本输入值 x 或 y 它应该显示来自 MongoDB 数据库的相关文档。

标签: rmongodbshiny

解决方案


您需要根据用户输入更改的查询。尝试将您的服务器代码更改为此。我正在考虑您的问题中有错字,您的实际输入是这样的textInput("doc_id", "Document type:", "")

服务器:

  mon <- mongo(collection = "collectionname", db = "db name", url = "mongodb://localhost:27017")

  # Create a reactive element. Changes when the user input changes
  data.for.table <- reactive({
    # Build a query that concatenates value of input$doc_id to other strings
    query.foo <- paste0('{"doc_type" : {"', input$doc_id, '" : ["x", "y"]} }' )
    # Retrieve data
    mon$find(query = query.foo, limit = 100)
  })

  output$mydata <- renderDataTable({
    data.for.table()
  })

推荐阅读