使用 C# driver 查询 MongoDB 中的深度嵌入文档
Query deeply embeded documents in MongoDB with C# driver
这只是一个示例代码...我已经设法使用 .$
获取了第三个嵌入文档,但没有进一步...如何查询第四个嵌套部分(文章标题)?
{
"bookTitle": "MongoDB",
"_id": ObjectId("530dea1d2dbf280000533b60"),
"bookChapters": [{
"chapterTitle": "chapterTitle",
"_id": ObjectId("530dea1d2dbf280000533b61"),
"chapterArticles": [{
"articleTitle": "articleTitle",
"_id": ObjectId("530dea1d2dbf280000533b62"),
"articleHeadings": [{
"headingTitle": "headingTitle",
"_id": ObjectId("530dea1d2dbf280000533b63")
}]
}]
}],
"__v": 0
}
您可以使用$elemMatch来匹配数组中的嵌套元素。我这里用了headingTitle
来匹配。查询将如下所示-
db.collection.find({
"bookChapters": {
"$elemMatch": {
"chapterArticles": {
"$elemMatch": {
"articleHeadings": {
"$elemMatch": {
"headingTitle": "headingTitle"
}
}
}
}
}
}
})
如果想转成mongo c#
驱动可以参考this
这只是一个示例代码...我已经设法使用 .$
获取了第三个嵌入文档,但没有进一步...如何查询第四个嵌套部分(文章标题)?
{
"bookTitle": "MongoDB",
"_id": ObjectId("530dea1d2dbf280000533b60"),
"bookChapters": [{
"chapterTitle": "chapterTitle",
"_id": ObjectId("530dea1d2dbf280000533b61"),
"chapterArticles": [{
"articleTitle": "articleTitle",
"_id": ObjectId("530dea1d2dbf280000533b62"),
"articleHeadings": [{
"headingTitle": "headingTitle",
"_id": ObjectId("530dea1d2dbf280000533b63")
}]
}]
}],
"__v": 0
}
您可以使用$elemMatch来匹配数组中的嵌套元素。我这里用了headingTitle
来匹配。查询将如下所示-
db.collection.find({
"bookChapters": {
"$elemMatch": {
"chapterArticles": {
"$elemMatch": {
"articleHeadings": {
"$elemMatch": {
"headingTitle": "headingTitle"
}
}
}
}
}
}
})
如果想转成mongo c#
驱动可以参考this