Search code examples
node.jsmongodbaggregatefacetobjectid

Mongodb aggregate facet won't work using _id


I have the following image below

enter image description here

enter image description here

I use _id but won't work but, when I use field like field_name is working.

I already use ObjectId("5f311...") still no luck

But when I use the query in robomongo client but using ObjectId("5f311...") it works.

I highly appreciate the help from you guys. I spent hours on this.

Thank you and keep safe.


Solution

  • use ObjectId of mongo like this:

    { $match: { _id: mongo.ObjectId("5f43ebb18415f39cf1cd75d4") } }

    complete example:

    let mongo = require("mongodb");
    
    let dbname = "test";
    let mongoServerUrl = "mongodb://127.0.0.1:27017/" + dbname;
    
    const connect = function () {
      return new Promise((resolve, reject) => {
        mongo.connect(
          mongoServerUrl,
          {
            useNewUrlParser: true,
            useUnifiedTopology: true,
          },
          (err, client) => {
            if (err) {
              reject(err);
            } else {
              let database = client.db(dbname);
              resolve(database);
            }
          }
        );
      });
    };
    
    connect()
      .then((database) => {
        console.log("connect to database");
    
        database
          .collection("new")
          .aggregate([
            {
              $facet: {
                query1: [
                  { $match: { _id: mongo.ObjectId("5f43ebb18415f39cf1cd75d4") } },
                ],
                query2: [
                  { $match: { _id: mongo.ObjectId("5f43ebb78415f39cf1cd75d5") } },
                ],
              },
            },
          ])
          .toArray(function (err, res) {
            if (err) {
              console.log(err);
            }
            console.log("get new done");
            console.log(res);
            console.log(res[0].query1);
          });
      })
      .catch((error) => {
        console.log(error);
      });