问题
Query for a MongoDB: From a given collection (see example below) I need only objects listed that comprise fields, where the field name starts with "need_".
Example of a collection with three objects
/* 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"
}
Desired Output:
/* 1 */
{
"_id" : 1,
"need_some" : "A",
"need_more" : 1,
"website_id" : "123456789"
}
/* 2 */
{
"_id" : 2,
"need_more" : 2,
"website_id" : "123456789"
}
Query could look something like
db.getCollection('nameCollection').find({ "need_.*" : { "$exists" : true }})
回答1:
You can use below aggregation using $objectToArray in mongodb 3.4 and above
db.collection.aggregate([
{ "$addFields": {
"field": { "$objectToArray": "$$ROOT" }
}},
{ "$match": { "field.k": { "$regex": "need_" }}},
{ "$project": { "field": 0 }}
])
Will give you output
[
{
"_id": 1,
"need_more": 1,
"need_some": "A",
"website_id": "123456789"
},
{
"_id": 2,
"need_more": 2,
"website_id": "123456789"
}
]
来源:https://stackoverflow.com/questions/53668269/mongodb-find-objects-with-field-names-starting-with