从对象嵌套数组mongodb中删除对象 [英] removing object from nested array of objects mongodb

查看:279
本文介绍了从对象嵌套数组mongodb中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收集了包含志愿者信息的收藏,并将志愿者列为一系列对象.我可以显示每个志愿者的所有班次,但是从阵列中删除一个对我来说很困难:

I've got collection with volunteer information in it, and it lists the volunteers as an array of objects. I can display all the shifts for each volunteer, but removing one from the array is proving difficult for me:

样本数据:

"_id" : ObjectId("59180305c19dbaa4ecd9ee59"),
    "where" : "Merchandise tent",
    "description" : "Sell gear at the merchandise tent.",
    "shifts" : [
            {
                    "dateNeeded" : ISODate("2017-06-23T00:00:00Z"),
                    "timeslot" : "8:00 - NOON",
                    "needed" : 2,
                    "_id" : ObjectId("591807546a71c3a57d1a2105"),
                    "volunteers" : [
                            {
                                    "fullname" : "Mary Mack",
                                    "phone" : "1234567890",
                                    "email" : "mary@gmail.com",
                                    "_id" : ObjectId("591ce45bc7e8a8c7b742474c")
                            }
                    ]
            },

我可用于此的数据是: _id,其中shifts.timeslot,shifts.dateNeeded,志愿者.email

The data I have available for this is: _id, where, shifts.timeslot, shifts.dateNeeded, volunteers.email

有人可以帮助我吗?可以说,玛丽·麦克(Mary Mack)希望在商品帐篷中取消参加8点-中午值班的志愿服务.她可能也被列为其他班次,但我们只想将她从此班次中删除.

Can someone help me? Lets say Mary Mack wants to unVolunteer for the 8 - Noon shift at the merchandise tent. She may be listed under other shifts as well, but we only want to remove her from this shift.

推荐答案

您可以通过指定一些内容来匹配文档",然后将所需的"shifts"数组条目作为.update()的查询表达式来执行此操作.然后将位置$运算符应用于匹配的数组索引与 $pull :

You can do this by specifying something to match the "document" and then the required "shifts" array entry as the query expression for an .update(). Then apply the positional $ operator for the matched array index with $pull:

db.collection.update(
 { "_id": ObjectId("59180305c19dbaa4ecd9ee59"), "shifts.timeslot": "8:00 - NOON" },
 { "$pull": { "shifts.$.volunteers": { "fullname": "Mary Mack" } } }
)

在这种情况下还可以,因为您只想在嵌套结构和

That is okay in this instance since you are only trying to "match" on the "outer" array in the nested structure and the $pull has query arguments of it's own to identify the array entry to remove.

您确实应该小心使用嵌套数组".在像这样的 $pull 操作起作用的同时,由于位置$运算符仅匹配满足条件的第一个"元素.因此,您在多个班次中使用"Mary Mack"的示例只能在找到的第一个班次"数组条目中进行匹配.

You really should be careful using "nested arrays" though. As whilst a $pull operation like this works, updates to the "inner" array are not really possible since the positional $ operator will only match the "first" element that meets the condition. So your example of "Mary Mack" in multiple shifts would only ever match in the first "shifts" array entry found.

这篇关于从对象嵌套数组mongodb中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆