Arrays 查询具有JSON文档数组的MongoDB集合
我有一个mongodb集合,格式如下:Arrays 查询具有JSON文档数组的MongoDB集合,arrays,mongodb,Arrays,Mongodb,我有一个mongodb集合,格式如下: { _id:"xxxx" comments : [ { comment:"I know good art is supposed to be controversial" commentid:"820168" username:"bleckfella" isprocessed:0
{
_id:"xxxx"
comments : [
{
comment:"I know good art is supposed to be controversial"
commentid:"820168"
username:"bleckfella"
isprocessed:0
},
{
comment:"Next thing.."
commentid:"820846"
username:"egzegs"
isprocessed:0
},
{
comment:"Good decision, please stay away Jamie."
commentid:"820901"
username:"Capt_mulch"
isprocessed:1
}
]
some fields.....
....
....
}
{
_id:"xxxx"
comments : [
{
comment:"who REALLY cares?"
commentid:"820162"
username:"BigBunny"
isprocessed:0
},
{
comment:"Double oh dear ..."
commentid:"820849"
username:"MrX"
isprocessed:1
},
{
comment:"Good decision."
commentid:"830501"
username:"mark11"
isprocessed:0
}
]
some fields.....
....
....
}
{
_id:"xxxx"
comments : [
{
comment:"my condolences Mick. My thoughts are with you."
commentid:"821164"
username:"BigBunny"
isprocessed:0
},
{
comment:"Three letters. O. M. G."
commentid:"840844"
username:"MrX"
isprocessed:0
}
]
some fields.....
....
....
}
现在我想查询这些数据,查找值为“isprocessed”字段为“1”的注释
我从shell尝试过的查询有:
db.coll.find({comments:{$elemMatch: {isProcessed:1}}},{"comments.isProcessed":1,"comments.comment":1}).pretty()
&
两者的输出相同,即:
{
_id : "xxxx"
"comments : [
{
comment:"I know good art is supposed to be controversial"
isprocessed:0
},
{
comment:"Next thing.."
isprocessed:0
},
{
comment:"Good decision, please stay away Jamie."
isprocessed:1
}
]
}
{
_id : "xxxx"
comments : [
{
comment:"who REALLY cares?"
isprocessed:0
},
{
comment:"Double oh dear ..."
isprocessed:1
},
{
comment:"Good decision."
isprocessed:0
}
]
}
这意味着它显示了我不需要的匹配文档的带有“isprocessed”字段值“0”的注释。
我需要输出为:
{
"_id":"xxxx"
comments : [
{
comment:"Good decision, please stay away Jamie."
isprocessed:1
}
]
}
{
_id:"xxxx"
comments : [
{
comment:"Double oh dear ..."
isprocessed:1
}
]
}
在以这种格式读取字段“isprocessed”后,我还需要更新其值。
如何为此编写查询。请建议任何解决方案。尝试以下命令
db.coll.aggregate([{$unwind: '$comments'}, {$match : {'comments.isprocessed' : 1}}, {$project : {_id : 1, 'comments.comment' : 1, 'comments.isprocessed' : 1}}])
它成功了。非常感谢你,迪克什。但还有一个问题。如何使用查询将此isprocessed字段从一个更改为0。表示要打印isprocessed值为0的记录。对吗?不,我想将数据库中isprocessed字段的值从1更新为0。此答案将能够帮助您。
db.coll.aggregate([{$unwind: '$comments'}, {$match : {'comments.isprocessed' : 1}}, {$project : {_id : 1, 'comments.comment' : 1, 'comments.isprocessed' : 1}}])