这是文档结构:
{
"_id":ObjectId("547366945785c02a7c993aaa"),
"RECNUM":"6310",
"ART_NR":"6385",
"ART_NRA":"11207604",
"ART_BEZ":{
"fr":"Coffret cadeau"
},
"BES1":{
"fr":"Service a fondue"
},
"markings":[
"CH-TP2",
"CH-WZ1",
"",
"EU-PAD002",
"",
""
]
}
我需要从标记数组中获取与正则表达式匹配的所有值:
'/^EU-/i'
给定的_id。所以在这种情况下回报如下:
{"markings": ["EU-PAD002"]}
我不知道如何进行这种查询,因为我对MongoDB不熟悉。
答案 0 :(得分:1)
如果您只想markings
,可以使用$projection
或使用aggregate
投影
db.coll.find({markings:{$regex:/^EU/ , $options:'i'}},{_id:0,markings:1})
聚合
db.coll.aggregate([
{
$match:{markings:/^EU-/i}
},{
$unwind:"$markings"
},{
$match:{markings:/^EU-/i}
},{
$group:{
_id:null,
markings:{$push:"$markings"}
}
},{
$project:{
_id:0,
markings:1
}
}
])
结果:
{
"result" : [
{
"markings" : [
"EU-PAD002"
]
}
],
"ok" : 1
}
查找有关$ regex http://docs.mongodb.org/manual/reference/operator/query/regex/和聚合http://docs.mongodb.org/manual/aggregation/
的内容答案 1 :(得分:1)
您可以使用aggregation framework
来实现您的目标。
db.mycollection.aggregate([
// Filter only those documents that at least have one match
{"$match": {markings:/^EU-/i}},
// De-normalize the markings array
{"$unwind": "$markings"},
// Filter all documents that match the reg exp
{"$match": {markings:/^EU-/i}},
// Re-construct the array
{"$group": {_id:"$_id", markings:{$push:"$markings"}}}
])
输出:
{
"result" : [
{
"_id" : ObjectId("547366945785c02a7c993aaa"),
"markings" : [
"EU-PAD002"
]
}
],
"ok" : 1
}
注意:如果您不希望结果中出现_id,则可以向汇总管道添加另一个$project
阶段。