Home > front end >  Mongoose retrieve documents if object keys exist
Mongoose retrieve documents if object keys exist

Time:04-27

I have a mongoose schema called Users :

let UserSchema = new mongoose.Schema({
firstname: {
  type: String,
  required: true,
},
lastname: {
  type: String,
  required: true,
},
houses: {
  type: Map,
  of: Array,
  required:[true,"No Units Detected"]
},
gender: {
  type: String,
  required: true,
},
email: {
  type: String,
  required: true,
  unique: true,
  lowercase: true,
  validate: (value) => {
    return validator.isEmail(value);
  },

},

Which leads to documents being saved as : Document 1:

    {
       firstname:"user1",
       lastname:"user",
       gender:"male",
       email:"[email protected]",
       houses: {
          "New York" : ['house1','house2']
          "Florida"  :  ['house1','house2']
      }
     }

Document 2:

    {
       firstname:"user2",
       lastname:"user",
       gender:"female",
       email:"[email protected]",
       houses: {
          "Florida"  :  ['house1']
          "Texas"    : ['house1']
      }
     }

the purpose of the schemas is to list the houses of each user even if the user has multiple houses in multiple states. My question is : Is there any query I could use to list the users in a certain state (which is a key inside an object) for example : Query for texas would return User 2 only , query for Florida would return user 1 and user 1

CodePudding user response:

Method 1: Use $exist

db.collection.aggregate([
  {
    $match: {
      "houses.Texas": { $exists: true }
    }
  }
])

mongoplayground


Method 2: Use $objectToArray

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $ne: [
          {
            $filter: {
              input: { $objectToArray: "$houses" },
              as: "h",
              cond: { $eq: [ "$$h.k", "Texas" ] }
            }
          },
          []
        ]
      }
    }
  }
])

mongoplayground

  • Related