gpt4 book ai didi

mongodb - 使用 mongodb 中的条件将字段添加到集合

转载 作者:行者123 更新时间:2023-12-05 08:39:19 25 4
gpt4 key购买 nike

我想将一个新的 bool 字段添加到包含其他字段信息的集合中。

我的样本数据是;

{ 
"_id" : ObjectId("50abae61edecb53c740022eb"),
"pull_request" : {
"diff_url" : null,
"patch_url" : null,
"html_url" : null
}
}
{
"_id" : ObjectId("50abae61edecb53c740022ec"),
"pull_request" : {
"diff_url" : "https://github.com/joyent/http-parser/pull/106.diff",
"patch_url" : "https://github.com/joyent/http-parser/pull/106.patch",
"html_url" : "https://github.com/joyent/http-parser/pull/106"
},
}

新字段是“hasPullRequest”;如果 pull_request 字段为 null,则 hasPullRequest:false;否则 hasPullRequest:true。我的意思是在下面;

{ 
"_id" : ObjectId("50abae61edecb53c740022eb"),
"pull_request" : {
"diff_url" : null,
"patch_url" : null,
"html_url" : null
},
"hasPullRequest" : false
}
{
"_id" : ObjectId("50abae61edecb53c740022ec"),
"pull_request" : {
"diff_url" : "https://github.com/joyent/http-parser/pull/106.diff",
"patch_url" : "https://github.com/joyent/http-parser/pull/106.patch",
"html_url" : "https://github.com/joyent/http-parser/pull/106"
},
"hasPullRequest" : true
}

我试过这个查询,但它没有运行;

db.getCollection('issues').aggregate([
{
$addFields: {
hasPullRequest: {
"$cond": {
if: { { "$eq": {"$pull_request": null}} ,
then: false,
else: true
}
}
}
])

我该怎么做?

最佳答案

因为有些记录没有pull_request字段,我加了一个or条件;

    db.getCollection("test").aggregate( [ 
{
$addFields: {
hasPullRequest: {
$cond: [
{
$or:
[
{ $and: [
{ $eq: [ "$pull_request.diff_url", null ] },
{ $eq: [ "$pull_request.patch_url", null ] },
{ $eq: [ "$pull_request.html_url", null ] },
]
},
{ $eq:[{ $ifNull: [ "$pull_request", 0 ] },0] }
]
},
false,
true
]
}
}
},
{
$out: "Issues2"
}
]
).pretty()

它非常适合我。

关于mongodb - 使用 mongodb 中的条件将字段添加到集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60169873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com