MongoDB从数组深两层拉元素 [英] MongoDB pull element from array two levels deep

查看:82
本文介绍了MongoDB从数组深两层拉元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下各项的收藏集:

I have a collection with the following items :

{ "Queries" : [  {  "Results" : [  {  "id" : 1 },  {  "id" : 2 } ] } ], "_id" : ObjectId("51ddb6f9b18996be485cba6f") }
{ "Queries" : [  {  "Results" : [  {  "id" : 0 },  {  "id" : 3 } ] } ], "_id" : ObjectId("51ddb701b18996be485cba70") }
{ "Queries" : [  {  "Results" : [  {  "id" : 1 },  {  "id" : 2 } ] } ], "_id" : ObjectId("51ddb705b18996be485cba71") }
{ "Queries" : [  {  "Results" : [  {  "id" : 1 },  {  "id" : 2 },  {  "id" : 4 } ] } ], "_id" : ObjectId("51ddb70db18996be485cba72") }
{ "Queries" : [  {  "Results" : [  {  "id" : 1 },  {  "id" : 2 },  {  "id" : null } ] } ], "_id" : ObjectId("51ddb7e4b18996be485cba73") }

我的文档上的查询"字段包含一系列子文档.这些子文档包含另一个子文档的数组.

The "Queries" field on my documents contains an array of subdocuments. These subdocuments contain an array of another subdocument.

我要删除结果"字段中文档"id"字段为1的所有条目.

I want to remove all entries in the "Results" field where the documents "id" field is 1.

我尝试了以下失败的尝试:

I tried the following without success :

update({}, {$pull :{"Queries.Results": {"id":1}}}, {"multi":true})
update({}, {$pull :{"Queries.Results.id":1}}, {"multi":true})

我将如何在MongoDB中实现这一目标?

How would I achieve this in MongoDB?

这是更新后find()的预期结果

Here is the expected result of find() after the update

{ "Queries" : [  {  "Results" : [  {  "id" : 2 } ] } ], "_id" : ObjectId("51ddb6f9b18996be485cba6f") }
{ "Queries" : [  {  "Results" : [  {  "id" : 0 },  {  "id" : 3 } ] } ], "_id" : ObjectId("51ddb701b18996be485cba70") }
{ "Queries" : [  {  "Results" : [  {  "id" : 2 } ] } ], "_id" : ObjectId("51ddb705b18996be485cba71") }
{ "Queries" : [  {  "Results" : [  {  "id" : 2 },  {  "id" : 4 } ] } ], "_id" : ObjectId("51ddb70db18996be485cba72") }
{ "Queries" : [  {  "Results" : [  {  "id" : 2 },  {  "id" : null } ] } ], "_id" : ObjectId("51ddb7e4b18996be485cba73") }

推荐答案

这是您必须使用的查询:

This is the query you have to use:

db.collection.update( { "Queries.Results.id":1 }, { $pull: { "Queries.$.Results": {"id":1} } } )

您需要指定"where"子句以找到要更新的文档. 您还缺少位置运算符$,您必须使用它,因为查询可以有多个结果.

You need to specify the "where" clause in order to find the document to update. You are also missing the positional operator $, you have to use it because Queries can have multiple Results.

这篇关于MongoDB从数组深两层拉元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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