bab*_*eyh 5 set mongodb conditional-statements aggregation-framework
我想将一个新的布尔字段添加到包含其他字段信息的集合中。
我的样本数据是;
{
"_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"
},
}
Run Code Online (Sandbox Code Playgroud)
新字段是“hasPullRequest”;如果 pull_request 字段为空,则 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
}
Run Code Online (Sandbox Code Playgroud)
我尝试了这个查询,但它没有运行;
db.getCollection('issues').aggregate([
{
$addFields: {
hasPullRequest: {
"$cond": {
if: { { "$eq": {"$pull_request": null}} ,
then: false,
else: true
}
}
}
])
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
由于有些记录没有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()
Run Code Online (Sandbox Code Playgroud)
它对我来说非常有效。
问题在于您的查询条件 - { "$eq": {"$pull_request": null}}
。它应该是以下之一:
db.test.aggregate( [
{
$addFields: {
hasPullRequest: {
$cond: [
{ $eq: [ "$pull_request", { diff_url: null, patch_url: null, html_url: null } ] },
false,
true
]
}
}
}
] ).pretty()
db.test.aggregate( [
{
$addFields: {
hasPullRequest: {
$cond: [
{ $and: [
{ $eq: [ "$pull_request.diff_url", null ] },
{ $eq: [ "$pull_request.patch_url", null ] },
{ $eq: [ "$pull_request.html_url", null ] }
] },
false,
true
]
}
}
}
] ).pretty()
Run Code Online (Sandbox Code Playgroud)
db.test.aggregate( [
{
$facet: {
pull_req_no: [
{ $match: { pull_request: { $exists: false } } },
{ $addFields: { hasPullRequest: false } }
],
pull_req_yes: [
{ $match: { pull_request: { $exists: true } } },
{ $addFields: {
hasPullRequest: {
$cond: [
{ $and: [
{ $eq: [ "$pull_request.diff_url", null ] },
{ $eq: [ "$pull_request.patch_url", null ] },
{ $eq: [ "$pull_request.html_url", null ] }
] },
false,
true
]
}
} }
]
}
},
{
$project: { result: { $concatArrays: [ "$pull_req_no", "$pull_req_yes" ] } }
},
{
$unwind: "$result"
},
{
$replaceRoot: { newRoot: "$result" }
}
] ).pretty()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
21356 次 |
最近记录: |