Home > front end >  How to return the key which value matches of an array in MongoDB?
How to return the key which value matches of an array in MongoDB?

Time:01-30

How do we query for matching values, and return its key. In this case, there is only 1 document in the DB.

const mongoose = require("mongoose");

const listSchema = new mongoose.Schema({
yuck: [String],
yumm: [String]
});

const List = mongoose.model("List", listSchema);

List.create({
yuck: [ "orange", "banana"],
yumm: ["broccoli", "chocolate"]
});

List.find({ $query: "chocolate" }, (err,result)=>{
console.log("Key is>>>", result);
});

//How do we query such that it will return the key whose value matches?
// Key is>>> yumm

CodePudding user response:

db.collection.aggregate([
  {
    "$match": {}
  },
  {
    "$set": {
      "arr": { "$objectToArray": "$$ROOT" }
    }
  },
  {
    "$set": {
      "arr": {
        "$filter": {
          "input": { $slice: [ "$arr", 1, { "$size": "$arr" }] },
          "as": "item",
          "cond": {
            "$in": [ "chocolate", "$$item.v" ]
          }
        }
      }
    }
  },
  {
    "$project": { key: { "$first": "$arr.k"} }
  }
])

mongoplayground

CodePudding user response:

Query

  • if your keys are not dynamic and they are only those 2 you can use this simplified way also
  • match to find which documents have "chocolate"
    (you can create 2 indexes on yumm/yuck to be fast)
  • condition to check in which one of the 2 "chocolate" exists

Test code here

aggregate(
[{"$match":
  {"$or":
   [{"yuck":{"$eq":"chocolate"}}, {"yumm":{"$eq":"chocolate"}}]}},
 {"$project":
  {"_id":0,
   "key":{"$cond":[{"$in":["chocolate", "$yuck"]}, "yuck", "yumm"]}}}])
  •  Tags:  
  • Related