Home > OS >  Return only matched key from Mongodb
Return only matched key from Mongodb

Time:07-09

I have a requirement where I want only matched key which is present in my docs.

Example :

my collection:

  users:
    [
      {
        name:"abc1",
        address:"address-abc"
      },
      {
        name:"pqr1",
        address:"address-pqr"
      },
      {
        name:"xyz2",
        address:"address-xyz"
      }
    ]

first query

const users = Users.aggregate([
  {
    $match:{$or:[{name:{$regex:"1"}},{address:{$regex:"bb"}}]}
  }
]);

will return

 [
  {_id:"6222222fdd",name:"abc1"},
  {_id:"4343553dfd",name:"pqr1"}
]

and

second query

const users = Users.aggregate([
  {
    $match:{$or:[{name:{$regex:"5"}},{address:{$regex:"dd"}}]}
  }
]);

will returns

 [
  {_id:"6222222fdd",address:"address-abc"},
  {_id:"4343553dfd",address:"address-pqr"},
  {_id:"64545454fd",address:"address-xyz"}
]

I am using aggregation pipeline. because requirement is fetch data from multiple collections based on previous stage.

CodePudding user response:

Query

  • if regex match keep the name else remove it
  • if regex match keep the address else remove it
  • if a document doesnt have both name and address remove it

Playmongo

aggregate(
[{"$set": 
   {"name": 
     {"$cond": 
       [{"$regexMatch": {"input": "$name", "regex": "1|5"}}, "$name",
        "$$REMOVE"]},
    "address": 
     {"$cond": 
       [{"$regexMatch": {"input": "$address", "regex": "dd|bb"}}, "$address",
        "$$REMOVE"]}}},
 {"$match": {"$expr": {"$or": ["$address", "$name"]}}}])
  • Related