我正在尝试构造一个 Mongodb 查询来返回一个字段值。我的 JSON 如下所示:
"question" : "Global_Deployment",
"displayOrder" : 1,
"answerOptions" : {
"fieldId" : "1001",
"fieldType" : "radiobutton",
"fieldName" : "Global Deployment?",
"fieldLabel" : "Global Deployment?",
"helpText" : "Help will go here",
"emailTagFormControl" : "Global_Deployment?",
"source" : "custom",
"status" : "active",
"required" : "true",
"multiSelect" : "false",
"purgeFlag" : "false",
"enableAuditTrack" : "false",
"fields" : [],
"fieldValue" : "Yes",
"options" : [
{
"optionName" : "Yes"
},
{
"optionName" : "No"
}
],
"comments" : {
"commentId" : "C1001",
"commentDetails" : []
}
我访问字段名称为“Global Deployment”的字段的查询是这样的:
db.getCollection('requests').find({"sections.questions.answerOptions.fieldName":"Global Deployment?"})
我想知道的是要添加到此查询中以返回“fieldValue”的值,该值位于 JSON 中的另一行。我是 Mongodb 的新手。任何帮助将不胜感激。
最佳答案
1) 如果数据库中有多个文档,其中 "fieldName": "Global Deployment?"
,则 . find()
将返回所有匹配的文档,即;在输出中,您得到的是一个文档数组,然后您需要迭代该数组以获取每个文档的 answerOptions.fieldValue
,检查下面的场景,正如我所解释的,有机会获得如果“sections.questions.answerOptions.fieldName”
不是唯一字段,则多个文档。
db.getCollection('requests').find({"sections.questions.answerOptions.fieldName":"Global Deployment?"}, {'sections.questions.answerOptions.fieldValue':1})
查找的输出:
/* 1 */
[{
"_id" : ObjectId("5d4e19826e173840500f5674"),
"answerOptions" : {
"fieldValue" : "Yes"
}
},
/* 2 */
{
"_id" : ObjectId("5d4e19826e073840500f5674"),
"answerOptions" : {}
}]
如果您只需要其中包含 fieldValue 的文档,请执行以下操作:
db.getCollection('requests').find({"sections.questions.answerOptions.fieldName":"Global Deployment?", 'sections.questions.answerOptions.fieldValue':{$exists: true}}, {'answerOptions.fieldValue':1})
好吧,现在您已经有了文档数组,然后迭代每个文档以检索您的值,请检查此 mongoDB cursor tutorial .
2) 如果您认为 fieldName
在整个集合中是唯一的,那么您可以使用 .findOne()
,这将准确返回一个文档(如果您有多个匹配文档,它将返回第一个找到的文档):
db.getCollection('requests').findOne({"sections.questions.answerOptions.fieldName":"Global Deployment?"}, {'sections.questions.answerOptions.fieldValue':1})
findOne 的输出:
{
"_id" : ObjectId("5d4e19826e173840500f5674"),
"answerOptions" : {
"fieldValue" : "Yes"
}
}
如果您看到 .find({},{})
有两个参数,第二个参数称为投影,如果您只想检索必填字段,它实际上很有用在响应中,默认情况下 mongoDB 将返回整个文档,您在问题中发布的内容都将被检索,mongoDB 中的数据以 JSON 形式流动,因此操作将与使用 JSON 类似,在这里您可以从结果中检索所需的字段,但为了充分利用网络效率,如果您不需要整个文档,则只能使用投影获取所需的字段。
关于Mongodb查询返回字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57436840/