MongoDB:查找字段名称以某个字符开头的对象

4

查询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 }})
1个回答

3
您可以在MongoDB 3.4及以上版本中使用以下聚合方法,使用$objectToArray操作符进行转换。
db.collection.aggregate([
  { "$addFields": {
    "field": { "$objectToArray": "$$ROOT" }
  }},
  { "$match": { "field.k": { "$regex": "need_" }}},
  { "$project": { "field": 0 }}
])

将为您提供输出结果

[
  {
    "_id": 1,
    "need_more": 1,
    "need_some": "A",
    "website_id": "123456789"
  },
  {
    "_id": 2,
    "need_more": 2,
    "website_id": "123456789"
  }
]

太棒了,谢谢。虽然花了一点时间,但是立刻就成功了。谢谢! - user2006697
太好了,感谢。花了一点时间,但立刻就起作用了。谢谢! - Ashh
哦,抱歉!它的意思是“非常好。花了一些时间,但它能够工作。非常感谢。” - user2006697

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接