如何用MongoDB查询筛选子文档数组并移除指定userId项?
MongoDB查询移除嵌套数组指定元素并返回完整文档
可以用MongoDB的聚合管道实现这个需求,核心是通过$map和$filter操作符处理嵌套数组,同时保留文档的所有原有字段。
聚合查询代码
db.collection.aggregate([ { $addFields: { users: { $map: { input: "$users", as: "user", in: { ..."$$user", userInteractions: { $filter: { input: "$$user.userInteractions", as: "interaction", cond: { $ne: ["$$interaction.userId.$oid", "633eb753c8e3d3fd71d1c254"] } } } } } } } } ])
代码说明
$addFields:替换users字段的同时,自动保留文档中其他字段(如_id、email)$map:遍历users数组,对每个用户对象进行处理$filter:在每个用户的userInteractions数组中,筛选出userId.$oid不等于目标ID的元素,从而移除指定的交互记录
示例文档
{ "_id": { "$oid": "633c25965034208db76cfb1e" }, "email": "test@test.com", "users": [ { "type": "person", "isActive": true, "userInteractions": [ { "userId": { "$oid": "633eb753c8e3d3fd71d1c254" }, "firstName": "Tom", "lastName": "Hawkins" }, { "userId": { "$oid": "633eb753c8e3d3fd71d1c222" }, "firstName": "Melan", "lastName": "Key" }, { "userId": { "$oid": "633eb753c8e3d3fd71d1c259" }, "firstName": "Ken", "lastName": "Olibar" } ] } ] }
预期输出
{ "_id": { "$oid": "633c25965034208db76cfb1e" }, "email": "test@test.com", "users": [ { "type": "person", "isActive": true, "userInteractions": [ { "userId": { "$oid": "633eb753c8e3d3fd71d1c222" }, "firstName": "Melan", "lastName": "Key" }, { "userId": { "$oid": "633eb753c8e3d3fd71d1c259" }, "firstName": "Ken", "lastName": "Olibar" } ] } ] }
内容的提问来源于stack exchange,提问作者Reno
相关产品推荐
相关产品推荐

