【发布时间】:2018-12-10 19:53:56
【问题描述】:
想象以下城市记录集合:
{
"city": "London",
"inhabitants": [
{
"id": "34543534",
"user": {
"name": "Jonathan Deer",
"email": "john@btinternet.com"
}
},
{
"id": "0454534",
"user": {
"name": "Tanya Patel",
"email": "tanya@btinternet.com"
}
},
{
"id": "4345345",
"user": {
"name": "Catherine King",
"email": "catherine@gmail.com"
}
}
]
}
{
"city": "Manchester",
"inhabitants": [
{
"id": "980003",
"user": {
"name": "Benjamin Thaw",
"email": "benny@btinternet.com"
}
},
{
"id": "734488",
"user": {
"name": "Craig Longstone",
"email": "craig@gmail.com"
}
},
{
"id": "4400093",
"user": {
"name": "Arnold Greentree",
"email": "arnold@btinternet.com"
}
},
]
},
我要做的是遍历每个城市的每个 inhabitants 数组,看看那里的人是否有一个包含 btinternet.com 的电子邮件地址在里面。对于那些我想发送一个新标志 isBT: true 的用户和其他所有人(例如 gmail.com 用户)isBT: false:
"user": {
"name": "Tanya Patel",
"email": "tanya@btinternet.com"
"isBT" true
}
我尝试了以下查询 - 第一个查询将所有查询设置为 isBT: false 而第二个查询在电子邮件地址中搜索“btinternet.com”并设置 isBT: true强>:
db.city.update({ "inhabitants.user.email": {$exists: true}}, {$set: { "inhabitants.$.user.isBT": false}}, {multi: true})
db.city.update({ "inhabitants.user.email": {$regex: "btinternet.com"}}, {$set: { "inhabitants.$.user.isBT": true}}, {multi: true})
问题是,当我执行第二个查询时,有几个居民记录留下了 isBT: false,即使它们包含必要的“btinternet.com”电子邮件地址。似乎只有第一个符合条件的用户记录才会更新...有没有办法更新所有“inhabitants”数组的所有用户记录? p>
我查看了使用位置运算符 $[],但我们的数据库是在 2.6.3 版本上,但这个运算符仅在 3.6 中引入...
【问题讨论】: