使用 $ne 查询后更新数组中的属性
我的集合 rooms
中的文档具有以下结构:
{
"_id": { "$oid": "4edaaa4a8d285b9311eb63ab" },
"users": [
{
"userId": { "$oid": "4edaaa4a8d285b9311eb63a9" },
"unreadMessages": 0
},
{
"userId": { "$oid": "4edaaa4a8d285b9311eb63aa" },
"unreadMessages": 0
},
]
}
如果我知道,我想增加第二个用户(数组中索引 1 处的用户)的 unreadMessages
第一个用户的ObjectId
。知道文档的 _id
就足以进行选择,但为了更新,我需要能够引用其他用户,所以我也按 users
进行选择。我通过以下更新调用来执行此操作:
collections.rooms.update(
{
_id: ObjectId("4edaaa4a8d285b9311eb63ab"),
users: { // not first user
$elemMatch: { $ne: { userId: ObjectId("4edaaa4a8d285b9311eb63a9") } }
}
},
{
// this should increment second user's unreadMessages,
// but does so for unreadMessages of first user
$inc: { "users.$.unreadMessages": 1 }
}
);
它会增加第一个用户的unreadMessages
,而不是第二个用户的unreadMessages
。我猜这是因为 $ne
实际上匹配第一个用户,显然这就是 users.$
所指的。
我应该如何修改此调用,以便第二个用户的 unreadMessages
增加?
A document in my collection rooms
has the following structure:
{
"_id": { "$oid": "4edaaa4a8d285b9311eb63ab" },
"users": [
{
"userId": { "$oid": "4edaaa4a8d285b9311eb63a9" },
"unreadMessages": 0
},
{
"userId": { "$oid": "4edaaa4a8d285b9311eb63aa" },
"unreadMessages": 0
},
]
}
I'd like to increment unreadMessages
of the second user (the one at index 1 in the array), if I know the ObjectId
of the first user. Knowing the _id
of the document is sufficient for selecting, but for updating I need to be able to reference to the other user, so I'm also selecting by users
. I'm doing so with the following update call:
collections.rooms.update(
{
_id: ObjectId("4edaaa4a8d285b9311eb63ab"),
users: { // not first user
$elemMatch: { $ne: { userId: ObjectId("4edaaa4a8d285b9311eb63a9") } }
}
},
{
// this should increment second user's unreadMessages,
// but does so for unreadMessages of first user
$inc: { "users.$.unreadMessages": 1 }
}
);
It increments unreadMessages
of the first user, not of the second user. I guess this is because $ne
actually matches on the first user, and apparently that's what users.$
is referring to.
How should I modify this call so that the second user's unreadMessages
is incremented?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你正在做正确的事情,除了 $ne 查询约束。
因此,
如果
我每次进行相同类型的交换时都得到五分钱……我就会得到很多五分钱。 :)
实际上,如果你想把事情变得更紧,那么 $elemMatch 并不是真正需要的,因为你只约束匹配数组元素的一个属性。我认为您可以将整个查询条件归结为:
I think you're doing the right thing, except for a little syntax dyslexia around the $ne query constraint.
So where you have
instead you want
If I had a nickel for every time I've done the same kind of swap ... I'd have a lot of nickels. :)
Actually, if you want to tighten things up, the $elemMatch is not really needed, since you're only constraining one property of the matched array element. I think you can boil the whole query criteria down to: