user10181542
user10181542

Reputation: 1380

Dynamic Match Variable Mongodb

I want to be able to pass a dynamic BSON variable to match for mongodb.

Here is what I have tried:

var query = "\"info.name\": \"ABC\"";

and

var query = {
    info: {
        name: "ABC"
    }
}

Neither of these work when passing variable 'query' to match (like below):

$match: {
   query
}

but explicitly passing like below does work:

$match: {
   "info.name": "ABC"
}

Upvotes: 4

Views: 4104

Answers (3)

t1maccapp
t1maccapp

Reputation: 343

As MongoDB documentation says:

To specify a query condition on fields in an embedded/nested document, use dot notation.

The actual problem is that you have your object property name as a variable in your JS code. Please, check how to add a property to a JavaScript object using a variable as the name.

Here is how you can do it:

var propertyName = "info.name"
var query = {}
query[propertyName] = "ABC"
...

Upvotes: 2

Ashok
Ashok

Reputation: 2932

Here is what went wrong

var query = "\"info.name\": \"ABC\"";
{ $match: ""info.name": "ABC"" } // This is single string

Here in this query, we get single string that's why not result filter But when you are using explicitly passing like this "info.name": "ABC" it work

For data

{ 
  _id: ObjectId(XXXXXXXXXX),
  info: { name: "ABC" }
}

You can use this aggregate query

// Create object and use this into [$match][1] stage
   const data = { "info.name": "ABC" };
// Use this object in match stag
         .aggregate([{ $match: data}])

if you have array of object then you need to use $elemMatch

For data

 {  
     _id: ObjectId(XXXXXXXXXX)
     info: [{ name: "ABC" }, { name: "DEF" } ]
}
// use elemMatch if array of object
     .aggregate([{ $match:  { info: { $elemMatch:{ name:  "ABC" }}}}])

Upvotes: 1

buræquete
buræquete

Reputation: 14698

It works when you pass a query object that is like;

var query = {
    "info.name": "ABC"
}

and passed into the aggregation pipe like so;

{ $match: query }

You can see its details on MongoDB Node.js Driver Tutorials


You cannot use a JSON object to query nested fields, like;

var query = {
    info: {
        name: "ABC"
    }
}

check here

unless info contains only name field, then it can be used in such a manner. But again you have to pass with { $match: query }, like here

Upvotes: 4

Related Questions