0

I have a mongoDb collection with following data:

{
 "material_name": "david",
 "material_unit": "87",
 "version": "1.0"
}

I am using following query field filter to fetch all material related fields which is working alright.

Query query = new Query();
query.fields().include("material_name");
query.fields().include("material_unit");
 

I have almost 100+ fields names which start with material. Is it possible to query fields with some kind of regex or any alternative approach?.

E.g.

Query query = new Query();
query.fields().include("material*");

1 Answer 1

2

I think the more efficient way is this one:

db.collection.aggregate([
   { $set: { data: { $objectToArray: "$$ROOT" } } },
   {
      $set: {
         data: {
            $filter: {
               input: "$data",
               cond: { $regexMatch: { input: "$$this.k", regex: "^material" } }
            }
         }
      }
   },
   { $replaceWith: { $arrayToObject: "$data" } }
])

You can also filter one the values like cond: { $eq: [ "$$this.v", "david" ] }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.