MongoDB: Find objects with field names starting with

时间秒杀一切 提交于 2020-01-24 11:11:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!