草庐IT

mongodb - $concat string with $cond in mongodb aggregation

coder 2023-11-07 原文

[
{
    "user_id" : 12453,
    "profile_type" : "demo_type_1",
    "records" : [
        {
            "type" : "typ_11",
            "value" : {
                "high" : 115,
                "low" : 78
            },
            "_meta" : {
                "data_type" : "text"
            }
        },
        {
            "type" : "type_1",
            "files" : [
                {
                    "title" : "path_prescription_1",
                    "url" : "/file_name.extension"
                },
                {
                    "title" : "path_prescription_2",
                    "url" : "/file_name__1.extension"
                }
            ],
            "_meta" : {
                "data_type" : "file"
            }
        }
    ]
},
{
    "user_id" : 12455,
    "profile_type" : "demo_type_1",
    "records" : [
        {
            "type" : "typ_11",
            "value" : {
                "high" : 115,
                "low" : 78
            },
            "_meta" : {
                "data_type" : "text"
            }
        },
        {
            "type" : "type_1",
            "files" : [
                {
                    "title" : "path_prescription_1",
                    "url" : "/file_name.extension"
                },
                {
                    "title" : "path_prescription_2",
                    "url" : "/file_name__1.extension"
                }
            ],
            "_meta" : {
                "data_type" : "file"
            }
        }
    ]
},
...
]

我想在 url 值前添加前缀,使其成为绝对路径,同时仅当 _meta 字段数据类型为文件而不是文本时才从数据库中检索。以上述格式存储,并仅使用附加的 url 以相同的格式检索。

有没有办法通过聚合管道来做到这一点?

最佳答案

您可以像这样尝试使用 $addFields:

db.getCollection('test').aggregate(

[

{
    $unwind: {
        path:"$records",

        preserveNullAndEmptyArrays: true
        }
},

{
    $unwind: {
        path:"$records.files",

        preserveNullAndEmptyArrays: true
        }
},

{
    $addFields: {
        "records.files.url":{
             $cond: {
                    if: {
                      $eq: ['$records.files', undefined]
                    },
                    then: null,
                    else: {$concat: ["some_prefix", "$records.files.url"]}
              }

            }
        }

    }

]

)

这会给你:

/* 1 */
{
    "_id" : ObjectId("5b6c484b9a8ea6a11c508520"),
    "user_id" : 12453.0,
    "profile_type" : "demo_type_1",
    "records" : {
        "type" : "typ_11",
        "value" : {
            "high" : 115.0,
            "low" : 78.0
        },
        "_meta" : {
            "data_type" : "text"
        },
        "files" : {
            "url" : null
        }
    }
}

/* 2 */
{
    "_id" : ObjectId("5b6c484b9a8ea6a11c508520"),
    "user_id" : 12453.0,
    "profile_type" : "demo_type_1",
    "records" : {
        "type" : "type_1",
        "files" : {
            "title" : "path_prescription_1",
            "url" : "some_prefix/file_name.extension"
        },
        "_meta" : {
            "data_type" : "file"
        }
    }
}

/* 3 */
{
    "_id" : ObjectId("5b6c484b9a8ea6a11c508520"),
    "user_id" : 12453.0,
    "profile_type" : "demo_type_1",
    "records" : {
        "type" : "type_1",
        "files" : {
            "title" : "path_prescription_2",
            "url" : "some_prefix/file_name__1.extension"
        },
        "_meta" : {
            "data_type" : "file"
        }
    }
}

/* 4 */
{
    "_id" : ObjectId("5b6c484b9a8ea6a11c508521"),
    "user_id" : 12455.0,
    "profile_type" : "demo_type_1",
    "records" : {
        "type" : "typ_11",
        "value" : {
            "high" : 115.0,
            "low" : 78.0
        },
        "_meta" : {
            "data_type" : "text"
        },
        "files" : {
            "url" : null
        }
    }
}

/* 5 */
{
    "_id" : ObjectId("5b6c484b9a8ea6a11c508521"),
    "user_id" : 12455.0,
    "profile_type" : "demo_type_1",
    "records" : {
        "type" : "type_1",
        "files" : {
            "title" : "path_prescription_1",
            "url" : "some_prefix/file_name.extension"
        },
        "_meta" : {
            "data_type" : "file"
        }
    }
}

/* 6 */
{
    "_id" : ObjectId("5b6c484b9a8ea6a11c508521"),
    "user_id" : 12455.0,
    "profile_type" : "demo_type_1",
    "records" : {
        "type" : "type_1",
        "files" : {
            "title" : "path_prescription_2",
            "url" : "some_prefix/file_name__1.extension"
        },
        "_meta" : {
            "data_type" : "file"
        }
    }
}

但是当记录类型为 text 时,请记住忽略 records.files.url 字段。

关于mongodb - $concat string with $cond in mongodb aggregation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51765947/

有关mongodb - $concat string with $cond in mongodb aggregation的更多相关文章

  1. ruby-on-rails - 在一个 Rails 应用程序中使用 PostgreSQL 的 MongoDB - 2

    我可以在一个Rails应用程序中同时使用MongoDB和PostgreSQL吗?具体来说,我最终会想要使用像MongoHQ这样的东西。到目前为止,我未能在实验中进行这项工作。令我担心的是,MongoDB文档特别指出我必须禁用ActiveRecord。任何建议将不胜感激。 最佳答案 您无需禁用ActiveRecord即可使用MongoDB。查看Mongoid只需将gem加上任何模型与您现有的任何ActiveRecord模型一起添加。您应该注意到MongoHQ只是MongoDB的托管服务,可以与任何对象文档映射器(ODM)一起使用。更多

  2. ruby - 使用 mongodb/mongoid 运行时更改模型 - 2

    我必须在mongoid模型中添加几个字段,我知道MongoDB没有迁移,但如果我继续而不删除数据库,使rails完全“重新生成”数据库,它不会显示或使用新的领域!去这里最好的方法是什么?有比删除/重新打开mongodb更软的东西吗?提前致谢卢卡 最佳答案 一般来说,应该可以在运行时用新字段更新旧文档。MongoDB中不需要迁移。您可能想编写rake任务以使用新字段和默认值更新旧文档。您可以通过检查那些默认值为nil的新字段来找到这些文档。更新简单风格:如果您使用默认值定义一个新字段,只要您设置了一个新值,就应该始终使用该值:应用程序

  3. ruby-on-rails - 我如何从 Ruby 代码连接到 mongodb? - 2

    我如何从Ruby代码连接到mongodb? 最佳答案 首先,您必须安装MongoDbgem:geminstallmongo然后运行代码:require'rubygems'#notnecessaryforRuby1.9require'mongo'db=Mongo::Connection.new.db("mydb")#ORdb=Mongo::Connection.new("localhost").db("mydb")#ORdb=Mongo::Connection.new("localhost",27017).db("mydb")

  4. ruby - MongoDB:无法从 BSON 类型 EOO 转换为 Date - 2

    我正在尝试使用聚合框架(使用ruby​​)并像这样投影日期:db['requests'].aggregate([{"$project"=>{_id:0,method:'$method',user:'$user',year:{'$year'=>'$timestamp'}}}])文档是这样的:{_id:ObjectId("5177d7d7df26358289da7dfd"),timestamp:ISODate("2013-04-12T03:58:05+00:00"),method:"POST",status:"200",inputsize:"874",outputsize:"4981",u

  5. ruby - 在 Ruby 中从 MongoDB 中检索字段的子集 - 2

    我试图通过在Ruby中进行的查询从MongoDB获取字段的子集,但它似乎不起作用。它不返回任何结果这是ruby代码:coll.find("title"=>'Halo',:fields=>["title","isrc"])#thisdoesn'twork如果我删除字段散列,它会工作,返回包含所有字段的结果coll.find("title"=>'Halo')#thisworks查看mongodb控制台,第一个查询在mongodb服务器上结束,如下所示:{title:"Halo",fields:["title","isrc"]}如果我尝试从mongo客户端控制台进行查询,它会工作,我会得到结

  6. Elasticsearch和MongoDB对比 - 2

    文章目录Elasticsearch和MongoDB对比关于ElasticsearchElasticsearch应用场景关于MongoDBMongoDB优点mongodb适用场景Elasticsearch和MongoDB对比Elasticsearch和MongoDB开源许可协议参考Elasticsearch和MongoDB对比关于Elasticsearch官网:https://www.elastic.co/cn/elasticsearch/Elasticistheleadingplatformforsearch-poweredsolutions.Weaccelerateresultsthatma

  7. javascript - 类型错误 : mongodb property insertmany is not a function - 2

    db.col.insertMany([{"_id":"tt0084726","title":"StarTrekII:TheWrathofKhan","year":1982,"type":"movie"},{"_id":"tt0796366","title":"StarTrek","year":2009,"type":"movie"},{"_id":"tt0084726","title":"StarTrekII:TheWrathofKhan","year":1982,"type":"movie"}]);OS:LinuxMint17.3RosaMongoDB:dbversionv2.6.1

  8. javascript - 如何使用 javascript 中的 http.post 将图像发送到服务器并在 mongodb 中存储 base64 - 2

    我在使用mongodb在服务器端存储图像的客户端访问http请求时遇到了问题。我非常感谢帮助。我需要一个简单的示例来说明如何将图像文件作为数据添加到httppost请求(例如XMLhttprequest)中。比方说,我知道服务器方法的网址。图片来源定义在imgsrc文件名存放在name我有这个自动取款机:varhttp=newXMLHttpRequest();httpPost.onreadystatechange=function(err){if(httpPost.readyState==4&&httpPost.status==200){console.log(httpPost.res

  9. 【MongoDB】windows安装MongoDB6.0.5+可视化界面软件 - 2

    目录MongoDB简介安装MongoDB  安装MongoDBShell添加账户密码 安装MongoDBCompassMongoDB简介MongoDB是一个流行的开源文档型NoSQL数据库管理系统,使用C++语言编写。与传统的关系型数据库不同,MongoDB使用文档模型来存储数据。文档模型是一种灵活的数据模型,它允许您在单个文档中存储和查询相关数据。文档模型还支持嵌套文档和数组结构,这使得它非常适合处理复杂的数据结构。MongoDB的特点包括:非常灵活的文档模型,可以轻松存储复杂数据类型。分布式系统设计,可以通过分片技术实现横向扩展,适合大规模数据处理。支持丰富的查询语言和聚合框架,使得开发人

  10. Helm部署minio\nginx\mongodb\elasticsearch - 2

    minioappVersion:2022-06-25chartVersion:11.7.7一、独立模式auth:auth:rootPassword:"12345678rtt"#密码长度需>=8位rootUser:"root"mode:standalone#默认为单机模式persistence:storageClass:minio-data#存储类,必填size:8Giservice:type:NodePort#暴露端口port:9000nodePort:31311二、分布式模式auth:auth:rootPassword:"12345678rtt"#密码长度需>=8位rootUser:"roo

随机推荐