具有嵌套结构的MongoDB查询

编程入门 行业动态 更新时间:2024-10-22 18:31:22
本文介绍了具有嵌套结构的MongoDB查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何查询(在MongoDB中)此嵌套的json结构,以便仅获取具有位置" 值等于"currentPosition" 值的嵌套对象?

How can I query (in MongoDB) this nested json structure in order to get only the nested object which has the "position" value equal to "currentPosition" value?

{ "JobId": "123" "currentPosition" : NumberInt(18), "details" : [ { "position": NumberInt(18), "fname" : "Alexander", "lname" : "A", }, { "position": NumberInt(18), "fname" : "Doug", "lname" : "D", }, { "position": NumberInt(15), "fname" : "Bruce", "lname" : "B", }, { "position": NumberInt(10), "fname" : "Tom", "lname" : "T", } ] }

目前,我正在通过python代码实现此目标:获取整个文档并遍历详细信息列表,以查找位置"值等于"currentPosition"值的对象.

Currently I am achieveing this by python code: getting the entire document and looping through the details list in order to find object with "position" value equal to "currentPosition" value.

最终输出看起来像

{ "JobId": "123" "currentPosition" : NumberInt(18), "details" : [ { "position": NumberInt(18), "fname" : "Alexander", "lname" : "A", }, { "position": NumberInt(18), "fname" : "Doug", "lname" : "D", } ] }

推荐答案

您将需要使用聚合框架.

You will need to use the aggregation framework for this.

details需要展开,以便您可以过滤掉不必要的详细信息.

details needs to be unwinded so that you can filter out the unnecessary details.

在$unwind阶段之后,您将有4个文档在管道中.在下一步中,您可以使用$match过滤掉您关心的细节.

After the $unwind stage you will have 4 documents in the pipeline. In the next stage you then use a $match to filter out the details you care about.

这意味着您将获得2个文档,这些文档具有相同的JobId和currentPosition,但具有不同的details

This means that as a result you will get 2 documents with the same JobId and currentPosition, but with different details

docs.mongodb/manual/reference/operator /aggregation/unwind

db.getCollection("DELETE_ME").aggregate( [ { $unwind: { path : "$details", } }, { $match: { "$expr": {"$eq": ["$details.position", "$currentPosition"]} } }, ] );

会返回

{ "_id" : ObjectId("---"), "JobId" : "123", "currentPosition" : NumberInt(18), "details" : { "position" : NumberInt(18), "fname" : "Alexander", "lname" : "A" } } { "_id" : ObjectId("---"), "JobId" : "123", "currentPosition" : NumberInt(18), "details" : { "position" : NumberInt(18), "fname" : "Doug", "lname" : "D" } }

更多推荐

具有嵌套结构的MongoDB查询

本文发布于:2023-11-22 20:43:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618951.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   结构   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!