skip to Main Content
{    
    "_id" : ObjectId("639789e84500571417ii9343"),
    "72uebaa27279b22p348e61870a6a8840something" : [ 
        {
            "price" : 130,
            "date" : 1670874476
        }, 
        {
            "price" : 107,
            "date" : 1672258500
        }
    ]
}


I need to find all documents where the second key contains string "something".

I only found a way to find by key name with "$exists", but I couldn’t find documents by statement mentioned above.

2

Answers


  1. You can use the following methods to perform a query in MongoDB with “like” regex:

    • Method 1: Find Documents that Contain String
    db.collection.find({name: {$regex : /string/i}})
    

    Note that the i indicates a case-insensitive match.

    • Method 2: Find Documents that Start with String
    db.collection.find({name: {$regex : /^string/i}}) 
    
    • Method 3: Find Documents that End with String
    db.collection.find({name: {$regex : /string$/i}}) 
    
    Login or Signup to reply.
  2. There is no way to query a fieldname with a substring or regular expression.

    It is possible to do that with aggregation, but this is not something an index can help with, so it will probably not perform well, and won’t scale well, because every such query would have to examine and process every document in the collection.

    The pipeline would need to:

    • convert the object to an array so the fieldname can be considered as data
    • match the desired critera
    • remove temporary fields or reconstitute the object
    db.collection.aggregate([
      {$addFields:{ arraydoc: {$objectToArray: "$$ROOT"}}},
      {$match: { "arraydoc.k": {$regex: "something"}}},
      {$project:{ arraydoc: 0}}
    ])
    

    Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search