Skip to content
Advertisement

mongodb project map fields to return from query with wildcard

I’m working on a system where I use a schema with the type Map much like this:

const Product = mongoose.model('Product', {
    name: String,
    data:{
        type:Map,
        of:String
    }
});

I’m trying to query certain parts of the docs in this collection with a projection:

Product.findOne({
    _id: req.params.id
}, {
   name:true,
   data.xy*
})

I would like to only get the fields in data starting with xy. Do you have any hint how to do that?

Advertisement

Answer

Since Mongoose’s map type will be represented as a nested object in mongodb, you could convert using $objectToArray which will result in array of key-value pairs that allows you to query by the keys starting with xy. Something like:

Product.aggregate([
  {
    $project: {
      data: {
        $objectToArray: "$data"
      }
    }
  },
  {
    "$unwind": "$data"
  },
  {
    $match: {
      "data.k": {
        $regex: "^xy"
      }
    }
  }
])

Here’s a working example on mongoplayground:

https://mongoplayground.net/p/yCJLhzalOXI

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement