问题描述
我正在尝试从Mongo数据库中提取特定的子元素。我使用了一组样本数据,其中包含圣经中的所有书籍和经文。我需要查询并显示单个经文。
数据如下:
Guid.Empty
我尝试了许多查询变体,但似乎无济于事。这是我尝试过的两个:
{"book": "1 Chronicles","chapters": [
{"chapter": "1","verses": [
{"verse": "1","text": "Adam,Sheth,Enosh,"},{"verse": "2","text": "Kenan,Mahalaleel,Jered,"}]},{"chapter": "2","verses": [
{"verse": "1","text": "These are the sons of Israel; Reuben,Simeon,Levi,"text": "Dan,Joseph,and Benjamin,Naphtali,Gad,and Asher."}]},{"chapter": "3","text": “etc etc…..”}]}]
}
我有MysqL的背景,所以也许我只是以错误的方式看待这个问题?
解决方法
这是.find()的基本投影功能无法完成的多个匹配项上的“数组过滤”。
您可以使用MongoDB aggregation framework来实现用例。
MongoDB的聚合框架以数据处理管道的概念为模型。文档进入多阶段流水线,将文档转换成汇总结果。
您可以在聚合管道中使用$project和$filter以获得最终结果。
db.collection.aggregate([
{
$match: {
"book": "1 Chronicles"
}
},{
"$project": {
"chapters": {
"$filter": {
"input": {
"$map": {
"input": "$chapters","as": "chapters","in": {
"chapter": "$$chapters.chapter","verses": {
"$filter": {
"input": "$$chapters.verses","as": "verses","cond": {
"$eq": [
"$$verses.verse","1"
]
}
}
}
}
}
},"cond": {
"$eq": [
"$$chapters.chapter","1"
]
}
}
}
}
}
])