0

Two documents containing ObjectId("6148a371c13a6a0be492ebf4")

Document 1

  {
           "_id" : ObjectId("6144f66fb9543917f96fc"),
           "refId" : "ford",
            "template" : "6144f61cb96d772317f96f9",
            "fieldValues" : {
                "PDV" : [ 
                    "6126938cd24a8aa3d37b4992", 
                    ObjectId("6148a371c13a6a0be492ebf4")
                ]
            },
            "group" : ObjectId("6144f66fb96d7731917f96fd"),
            "createdAt" : ISODate("2021-09-17T20:11:27.440Z"),
            "updatedAt" : ISODate("2021-09-20T15:06:26.146Z"),
            "__v" : 0
  }

Document 2

 {
            "_id" : ObjectId("6144f66fb96d77rr3217f96fc"),
            "refId" : "CCM",
            "template" : "6144f613296d7731917f96f9",
            "fieldValues" : {
                "DDB" : [ 
                    "6126938cd2448aa3d37b4992", 
                    "5443938cd2448aa3d37b4992", 
                    ObjectId("6148a371c13a6a0be492ebf4"),
                ]
            },
            "group" : ObjectId("6144f66fb96de431917f96fd"),
            "createdAt" : ISODate("2021-09-17T20:11:27.440Z"),
            "updatedAt" : ISODate("2021-09-20T15:06:26.146Z"),
            "__v" : 0
 }

ObjectId that we looking for is always inside fieldValues but instead of PDV or DDB we will always have the different naming.

So we can't use this type of query: db.getCollection('products').find({"fieldValues.PDV":ObjectId('6148a371c13a6a0be492ebf4')})


PS. This query should work only on DB, we can't afford to query all products and do calculation on backend there might to be a millions of products.

Qui-Gon Jinn
  • 3,722
  • 3
  • 25
  • 32

3 Answers3

1

You can use this one:

db.collection.aggregate([
  {
    $set: {
      kv: { $first: { $objectToArray: "$fieldValues" } }
    }
  },
  { $match: { "kv.v": ObjectId("6148a371c13a6a0be492ebf3") } },
  { $unset: "kv" }
])

Mongo Playground

Wernfried Domscheit
  • 54,457
  • 9
  • 76
  • 110
0

db.products.find({'_id': ObjectId("6148a371c13a6a0be492ebf4")})

The mistake in your code is that you used key instead of _id.

This way of writing it is much easier on the fingers though.

Neptune
  • 40
  • 1
  • 6
0

You'd think a solution like this would work but one reason why this may not is because you're trying to use === on an object. If you refer to this thread, it might help if you use .equals() instead of ===.

Derek Kim
  • 190
  • 2
  • 11