MongoDb查询以匹配和删除数组中的元素? [英] MongoDb query to match and remove elements from an array?

查看:183
本文介绍了MongoDb查询以匹配和删除数组中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要查询并从设施中删除一个ID,该ID存储了一组设施ID. 我的架构.

I wana query and remove an id from the facilities which stores an array of facility Ids. My Schema.

 {
        "_id" : ObjectId("zzzzzzzzzzzzzzzzzzzzz"),
        "account" : {
            "createdOn" : ISODate("2016-02-19T10:31:32.918Z"),

        },
        "appointments" : [],
        "facilities" : [ 
            ObjectId("vvvvvvvvvvvvvvvvvvvvvvvvvvvv"),
            ObjectId("xxxxxxxxxxxxxxxxxxxxxxxxxxxxx")

我尝试过,但是它删除了整个模式?

I tried this but Its deleting the whole schema??

  this.remove({ '_id': id, facilities :  { "$in" : [facilityId]} })

此处, id 是此架构的ID, facilityId 是来自设施的ID.任何帮助将不胜感激?

Here the id is the ID of this schema and facilityId is an id from the facilities. Any help would be very grateful??

推荐答案

您要保留文档并从设施"数组中删除一个元素吗?是这个吗?

You want to keep the document and remove an element from the "facilities" array? Is this it?

如果是这样,您不想"删除",而是"更新"您的文档.

If so, you don't want to "remove", but "update" your document.

它会以这种方式出现:

update(
  {
    "_id": id
  },
  {
    $pullAll:
    {
      "facilities": [facilityId]
    }
  }
)

PS:我假设您要修改文档时已经拥有您的文档ID.如果没有,您可以通过设施"字段进行查询(使用 $ in 运算符,就像您所做的那样),在这种情况下,最好在它上面有一个索引.正如其他答案所提到的,您也可以在查询字段上有一个空文档,但是这样做的效果通常很差.

PS: I assumed you already have your document id on hands when you want to modify it. If not, you could query by the "facilities" fields (with $in operator, like you did), and, in that case, you would better have an index on it. You could also, as the other answers mention, have an empty document on the query field, but this tends to perform very poorly.

这篇关于MongoDb查询以匹配和删除数组中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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