查询 MongoDB:从给定的集合(参见下面的示例)中,我只需要列出包含字段的对象,其中字段名称以“need_”开头。
包含三个对象的集合示例
/* 1 */
{
"_id" : 1,
"need_some" : "A",
"need_more" : 1,
"website_id" : "123456789"
}
/* 2 */
{
"_id" : 2,
"need_more" : 2,
"website_id" : "123456789"
}
/* 3 */
{
"_id" : 3,
"website_id" : "123456789"
}
期望的输出:
/* 1 */
{
"_id" : 1,
"need_some" : "A",
"need_more" : 1,
"website_id" : "123456789"
}
/* 2 */
{
"_id" : 2,
"need_more" : 2,
"website_id" : "123456789"
}
查询可能类似于
db.getCollection('nameCollection').find({ "need_.*" : { "$exists" : true }})
您可以使用以下聚合$objectToArray https://docs.mongodb.com/manual/reference/operator/aggregation/objectToArray/在 mongodb 中3.4以上
db.collection.aggregate([
{ "$addFields": {
"field": { "$objectToArray": "$$ROOT" }
}},
{ "$match": { "field.k": { "$regex": "need_" }}},
{ "$project": { "field": 0 }}
])
会给你output https://mongoplayground.net/p/b67Zr4uGzh0
[
{
"_id": 1,
"need_more": 1,
"need_some": "A",
"website_id": "123456789"
},
{
"_id": 2,
"need_more": 2,
"website_id": "123456789"
}
]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)