[英]How to fetch data in a single go from mongodb based on multiple filters?
[英]How to fetch the list of data from nested json in MongoDb based on key?
我在MongoDB中有一個JSON,集合名稱為StudentData:
"data" : {
"students":{
"A":{
"roll":"11",
"otherDetails":{
"name":"AAA"
}
},
"B":{
"roll":"12",
"otherDetails":{
"name":"BBB"
}
},
"C":{
"roll":"13",
"otherDetails":{
"name":"CCC"
}
},
"D":{
"roll":"14",
"otherDetails":{
"name":"DDD"
}
}
}
}
如何獲取所有學生A
,我嘗試了以下db.StudentData.find({"data.students":"A"})
但未返回任何內容。
我試圖得到這個:
{
"roll":"11",
"otherDetails":{
"name":"AAA"
}
}
什么是Java等效查詢和Mongo等效查詢?
A
is對象,但是您將其作為值來獲取。 因此,它什么也沒有給您。 嘗試這個:
db.collection.find({},
{
"data.students.A": 1
})
這是@MilanRegmi建議的簡單方法
雖然,我只是想添加其他使用聚合的可能方式。
db.collections.aggregate([
{ $addFields: { studentsList: { $objectToArray: "$data.students" } } },
{ $match: { "studentsList.k": "A" }},
{ $project: {
students: { $filter: {
input: '$studentsList',
as: 'student',
cond: { $eq: [ '$$student.k', 'A' ]}
}},
_id: 0
}},
{ $unwind: "$students" }, // Not required if you are ok with having some nested array
{ $replaceRoot: { newRoot: "$students.v" }} // Not required if you are ok with having some nested array
])
還有一個優化的查詢是:
db.collection.aggregate([
{ $addFields: { studentsList: { $objectToArray: "$data.students" } } },
{ $unwind: "$studentsList" },
{ $match: { "studentsList.k": "A" }},
{ $replaceRoot: { newRoot: "$studentsList.v" }} // Not required if you are ok with having object with some other fields
])
輸出:( 對於兩個查詢)
/* 1 */
{
"roll" : "11",
"otherDetails" : {
"name" : "AAA"
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.