【发布时间】:2023-01-14 00:11:41
【问题描述】:
我有一个嵌入在文档中的对象数组,并且集合中有多个这样的文档。 如何查询具有以下条件的那些嵌入式对象数组(基于我下面的文档)。
-
首先获取
"status"为"active"的对象(状态不会出现在所有对象中,只会出现在少数对象中) -
然后得到上面满足的对象的
"parent_user_id",和剩下的对象"parent_user_id"匹配,得到那些对象 -
必须设置上述条件的结果,而不是输出中对象的原始数组(即:
"users"),而不是所有存在的对象。 因此,如果您查看结果,我预计用户数组中缺少 3 个元素,因为这些元素不满足上述条件。 我收集的文件(将有多个文件){ "_id" : ObjectId("63a8808652f40e1d48a3d1d7"), "name" : "A", "description" : null, "users" : [ { "id" : "63a8808c52f40e1d48a3d1da", "owner" : "John Doe", "purchase_date" : "2022-12-25, "status" : "active", "parent_user_id" : "63a8808c52f40e1d48a3d1da", "recent_items": ["tomato",onion] }, { "id" : "63a880a552f40e1d48a3d1dc", "owner" : "John Doe 1", "purchase_date" : "2022-12-25, "parent_user_id" : "63a8808c52f40e1d48a3d1da", "recent_items": ["onion"] }, { "id" : "63a880f752f40e1d48assddd" "owner" : "John Doe 2", "purchase_date" : "2022-12-25, "parent_user_id" : "63a8808c52f40e1d48a3d1da", }, { "id" : "63a880f752f40e1d48a3d207" "owner" : "John Doe 11", "dt" : "2022-12-25, "status" : "inactive", "parent_user_id" : "63a880f752f40e1d48a3d207", }, { "id" : "63a880f752f40e1d48agfmmb" "owner" : "John Doe 112", "dt" : "2022-12-25, "status" : "active", "parent_user_id" : "63a880f752f40e1d48agfmmb", "recent_items": ["tomato"] } { "id" : "63a880f752f40e1d48agggg" "owner" : "John SS", "dt" : "2022-12-25, "status" : "inactive", "parent_user_id" : "63a880f752f40e1d48agggg", } { "id" : "63a880f752f40e1d487777" "owner" : "John SS", "dt" : "2022-12-25, "parent_user_id" : "63a880f752f40e1d48agggg", } ] }结果很期待
{ "_id" : ObjectId("63a8808652f40e1d48a3d1d7"), "name" : "A", "description" : null, "users" : [ { "id" : "63a8808c52f40e1d48a3d1da", "owner" : "John Doe", "purchase_date" : "2022-12-25, "status" : "active", "parent_user_id" : "63a8808c52f40e1d48a3d1da", "recent_items": ["tomato",onion] }, { "id" : "63a880a552f40e1d48a3d1dc", "owner" : "John Doe 1", "purchase_date" : "2022-12-25, "parent_user_id" : "63a8808c52f40e1d48a3d1da", }, { "id" : "63a880f752f40e1d48assddd" "owner" : "John Doe 2", "purchase_date" : "2022-12-25, "parent_user_id" : "63a8808c52f40e1d48a3d1da", }, { "id" : "63a880f752f40e1d48agfmmb" "owner" : "John Doe 112", "dt" : "2022-12-25, "status" : "active", "parent_user_id" : "63a880f752f40e1d48agfmmb", "recent_items": ["tomato"] } ] }
【问题讨论】:
标签: mongodb aggregation-framework aggregate