Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Find objects with field names starting with

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 }})
like image 468
user2006697 Avatar asked Oct 16 '25 19:10

user2006697


1 Answers

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"
  }
]
like image 152
Ashh Avatar answered Oct 18 '25 13:10

Ashh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!