MongoDB:查找字段名称开头为的对象 [英] MongoDB: Find objects with field names starting with

查看:1076
本文介绍了MongoDB:查找字段名称开头为的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查询MongoDB:从给定的集合中(请参见下面的示例),我只需要列出包含字段的对象,其中字段名称以"need_"开头.

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"
}

所需的输出:

/* 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 在mongodb 3.4 及更高版本中

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"
  }
]

这篇关于MongoDB:查找字段名称开头为的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆