如何强制MongoDB pullAll忽略文档顺序 [英] How to force MongoDB pullAll to disregard document order

查看:237
本文介绍了如何强制MongoDB pullAll忽略文档顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下结构的mongoDB文档:

I have a mongoDB document that has the following structure:

{
    user:user_name, 
    streams:[
        {user:user_a, name:name_a}, 
        {user:user_b, name:name_b},
        {user:user_c, name:name_c}
    ]
}

我想使用$ pullAll从streams数组中删除,并向其传递一个streams数组(该数组的大小从1到N不等):

I want to use $pullAll to remove from the streams array, passing it an array of streams (the size of the array varies from 1 to N):

var streamsA = [{user:"user_a", name:"name_a"},{user:"user_b", name:"name_b"}]
var streamsB = [{name:"name_a", user:"user_a"},{name:"name_b", user:"user_b"}]

我使用以下mongoDB命令执行更新操作:

I use the following mongoDB command to perform the update operation:

db.streams.update({name:"user_name", {"$pullAll:{streams:streamsA}})
db.streams.update({name:"user_name", {"$pullAll:{streams:streamsB}})

删除streamA成功,而删除streamB失败.深入研究mongoDB手册之后,我发现streamA和streamB记录中的字段顺序必须与数据库中的字段顺序匹配.对于streamsB,该顺序不匹配,这就是为什么未将其删除的原因.

Removing streamsA succeeds, whereas removing streamsB fails. After digging through the mongoDB manuals, I saw that the order of fields in streamsA and streamsB records has to match the order of fields in the database. For streamsB the order does not match, that's why it was not removed.

在执行更新操作之前,我可以将流重新排序为数据库文档顺序,但是是否有更简单,更干净的方法来执行此操作?是否可以设置一些标志来更新和/或pullAll来忽略该顺序?

I can reorder the streams to the database document order prior to performing an update operation, but is there an easier and cleaner way to do this? Is there some flag that can be set to update and/or pullAll to ignore the order?

谢谢, 加里

推荐答案

$pullAll 运算符实际上是一个特殊情况",主要用于单个标量"数组元素,而不是用于使用它的子文档.

The $pullAll operator is really a "special case" that was mostly intended for single "scalar" array elements and not for sub-documents in the way you are using it.

请改为使用 $pull ,它将检查每个元素并使用 $or > 文档列表的条件:

Instead use $pull which will inspect each element and use an $or condition for the document lists:

db.streams.update(
    { "user": "user_name" },
    { "$pull": { "streams": { "$or": streamsB } }}
)

通过这种方式,字段的顺序或实际上是否在寻找精确匹配"都无关紧要,因为当前$pullAll操作实际上正在执行该操作.

That way it does not matter which order the fields are in or indeed look for an "exact match" as the current $pullAll operation is actually doing.

这篇关于如何强制MongoDB pullAll忽略文档顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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