Mongodb从子数组更新特定元素

编程入门 行业动态 更新时间:2024-10-26 16:28:42
本文介绍了Mongodb从子数组更新特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个具有以下架构的集合:

I have a collection with a following schema:

{ "_id" : 28, "n" : [{ "a" : ObjectId("4ef8466e46b3b8140e000000"), "c" : 28, "p" : [ObjectId("4f00640646b3b88005000003"), ObjectId("4f00640146b3b88005000002"), ObjectId("4f00637d46b3b8cc0e000001"), ObjectId("4f00638046b3b8cc0e000002"), ObjectId("4f00638246b3b8cc0e000003"), ObjectId("4f00631646b3b85002000001"), ObjectId("4f00631846b3b85002000002")], "u" : 26 }, { "a" : ObjectId("4ef8466e46b3b8140e000000"), "c" : 10, "p" : [ObjectId("4f00640146b3b88005000002"), ObjectId("4f0063fd46b3b88005000001")], "u" : 26 }, { "a" : ObjectId("4ef8467846b3b8780d000001"), "u" : 26, "p" : [ObjectId("4f00637b46b3b8cc0e000000")], "c" : 28 }, { "a" : ObjectId("4ef85a3e46b3b84408000000"), "u" : 26, "p" : [ObjectId("4f00631046b3b85002000000")], "c" : 28 }] }

我需要使用_id = 28更新文档数组中的元素之一 但是只有当a =某个值而c =某个值

I need to update one of the elements in the array in the document with _id = 28 but only if the a = to some value and c = some value

db.coll.update({ '_id' : 28, 'n.a' : new ObjectId('4ef85a3e46b3b84408000000'), 'n.c' : 28 }, { $push : { 'n.$.p' : ObjectId("4b97e62bf1d8c7152c9ccb74") }, $set : { 'n.$.t' : ISODate("2013-05-13T14:22:46.777Z") } })

所以基本上我想从数组更新特定元素: 据人们所知,这是第四个要素.问题是执行查询时,很可能会更新第一个元素.

So basically I want to update specific element from array: and as far as one can see, this is the fourth element. The problem is that when the query is executing, it most likely updates the first element.

我该如何解决?

推荐答案

您的代码中的问题是dot-notation,因为当您指定点表示法时,您假定指定的过滤条件必须与满足所有条件的单个数组元素匹配标准.但事实并非如此.如果有任何单个条件匹配,则阵列上的点符号可以拾取任何阵列元素.这就是为什么您得到意外更新的原因.

The problem in your code is dot-notation because When you specify the dot notation you assume that the filter criterias specified must match the single array element that satisfies all the criteria. But it doesnt. Dot notation on arrays may pickup any array element if any single criteria matches. Thats why you are getting the unexpected update.

您必须使用 $elemMatch 进行匹配array元素中的所有过滤器.

You have to use $elemMatch to match all the filters in the array element.

db.coll.update({ '_id' : 28, n: { $elemMatch:{ a : new ObjectId('4ef85a3e46b3b84408000000'), c : 28 } } }, { $push : { 'n.$.p' : ObjectId("4b97e62bf1d8c7152c9ccb74") }, $set : { 'n.$.t' : ISODate("2013-05-13T14:22:46.777Z") } })

输出为

{ "a" : ObjectId("4ef85a3e46b3b84408000000"), "c" : 28, "p" : [ ObjectId("4f00631046b3b85002000000"), ObjectId("4b97e62bf1d8c7152c9ccb74") ], "t" : ISODate("2013-05-13T14:22:46.777Z"), "u" : 26 }

更多推荐

Mongodb从子数组更新特定元素

本文发布于:2023-10-23 18:58:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1521726.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   元素   从子   Mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!