0

I want to get a specific element of the array and through the responsaveis.$ (daniela.morais@sofist.com.br) but there is no result, there is problem in my syntax?

{
    "_id" : ObjectId("54fa059ce4b01b3e086c83e9"),
    "agencia" : "Abc",
    "instancia" : "dentsuaegis",
    "cliente" : "Samsung",
    "nomeCampanha" : "Serie A",
    "ativa" : true,
    "responsaveis" : [ 
        "daniela.morais@sofist.com.br", 
        "abc@sofist.com.br"
    ],
    "email" : "daniela.morais@sofist.com.br"
    }

Syntax 1

mongoCollection.findAndModify("{'responsaveis.$' : #}", oldUser.get("email"))
                .with("{$set : {'responsaveis.$' : # }}", newUser.get("email"))
                .returnNew().as(BasicDBObject.class);

Syntax 2

db.getCollection('validatag_campanhas').find({"responsaveis.$" : "daniela.morais@sofist.com.br"})

Result

Fetched 0 record(s) in 1ms
Daniela Morais
  • 2,125
  • 7
  • 28
  • 49

2 Answers2

1

The $ positional operator is only used in update(...) or project calls, you can't use it to return the position within an array.

The correct syntax would be :-

Syntax 1

mongoCollection.findAndModify("{'responsaveis' : #}", oldUser.get("email"))
                .with("{$set : {'responsaveis.$' : # }}", newUser.get("email"))
                .returnNew().as(BasicDBObject.class);

Syntax 2

db.getCollection('validatag_campanhas').find({"responsaveis" : "daniela.morais@sofist.com.br"})

If you just want to project the specific element, you can use the positional operator $ in projection as

{"responsaveis.$":1}

db.getCollection('validatag_campanhas').find({"responsaveis" : "daniela.morais@sofist.com.br"},{"responsaveis.$":1})
thegreenogre
  • 1,559
  • 11
  • 22
0

Try with this

db.validatag_campanhas.aggregate(
  { $unwind : "$responsaveis" },
      { 
        $match  : {
         "responsaveis": "daniela.morais@sofist.com.br"
      }
  },
  { $project : { responsaveis: 1, _id:0 }}
);

That would give you all documents which meets that conditions

{
    "result" : [
        {
            "responsaveis" : "daniela.morais@sofist.com.br"
        }
    ],
    "ok" : 1
}

If you want one document that has in its responsaveis array the element "daniela.morais@sofist.com.br" you can eliminate the project operator like

db.validatag_campanhas.aggregate(
  { $unwind : "$responsaveis" },
      { 
        $match  : {
         "responsaveis": "daniela.morais@sofist.com.br"
      }
  }
);

And that will give you

{
    "result" : [
        {
            "_id" : ObjectId("54fa059ce4b01b3e086c83e9"),
            "agencia" : "Abc",
            "instancia" : "dentsuaegis",
            "cliente" : "Samsung",
            "nomeCampanha" : "Serie A",
            "ativa" : true,
            "responsaveis" : "daniela.morais@sofist.com.br",
            "email" : "daniela.morais@sofist.com.br"
        }
    ],
    "ok" : 1
}

Hope it helps