如何在mongodb中的对象数组数组中搜索 [英] How to search in array of array of object in mongodb

查看:33
本文介绍了如何在mongodb中的对象数组数组中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设 mongodb 文档(表)'users' 是

{"_id": "6065923bc5d509071857f6e6",版本": [{"name": "1.1.0","状态": "未批准","_id": "606592b1c5d509071857f6e7",文件":[{"_id": "606592b3c5d509071857f6e8","url": "https://google.com/1.png",状态":等待"},{"_id": "606592b8c5d509071857f6e9","url": "https://google.com/2.png",状态":等待"}]}]}

我想更新这个***

Suppose the mongodb document(table) 'users' is

{
    "_id": "6065923bc5d509071857f6e6",
    "version": [
        {
            "name": "1.1.0",
            "status": "not Approved",
            "_id": "606592b1c5d509071857f6e7",
            "files": [
                {
                    "_id": "606592b3c5d509071857f6e8",
                    "url": "https://google.com/1.png",
                    "status": "awaiting"
                },
                {
                    "_id": "606592b8c5d509071857f6e9",
                    "url": "https://google.com/2.png",
                    "status": "awaiting"
                }
            ]
        }
    ]
}

I want to update the status of this "***https://google.com/1.png***" image Can we do using findOneAndUpdate? because i want to return the updated Object

解决方案

Let's say you want to search for the awaiting status for the collection users

db.users.find({"version.files.status":"awaiting"}).pretty()

It will automatically search within the arrays.

Updating, however, is a bit different and you should use arrayFilter:

db.users.updateOne(
  {
    "version.files._id": "606592b3c5d509071857f6e8",
  },
  {
    $set: {
      "version.$[version].files.$[file].url": "something else",
    },
  },
  {
    arrayFilters: [
      { "version._id": "606592b1c5d509071857f6e7" },
      { "file._id": "606592b3c5d509071857f6e8" },
    ],
  }
);

Make sure to have an index on your find query:

For the above example

db.users.createIndex({"version.files._id":1},{background:true})

Many more example available on the Mongo Doc


EDIT

As per your comment, here is a working example:

db.users.findOneAndUpdate(
  { "version.files._id": "606592b3c5d509071857f6e8" },
  {
    $set: {
      "version.$[version].files.$[file].url": "Test URL",
      "version.$[version].files.$[file].status": "Test status",
    },
  },
  {
    returnNewDocument: true,
    arrayFilters: [
      { "version._id": "606592b1c5d509071857f6e7" },
      { "file._id": "606592b3c5d509071857f6e8" },
    ],
  }
);

这篇关于如何在mongodb中的对象数组数组中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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