0

我想通过responsaveis.$(daniela.morais@sofist.com.br) 获取数组的特定元素但没有结果,我的语法有问题吗?

{
    "_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"
    }

语法 1

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

语法 2

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

结果

Fetched 0 record(s) in 1ms
4

2 回答 2

1

$位置运算符仅用于 update(...) 或项目调用,您不能使用它返回数组中的位置。

正确的语法是:-

语法 1

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

语法 2

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

如果您只想投影特定元素,可以$在投影中使用位置运算符作为

{"responsaveis.$":1}

db.getCollection('validatag_campanhas').find({"responsaveis" : "daniela.morais@sofist.com.br"},{"responsaveis.$":1})
于 2015-04-17T18:35:38.213 回答
0

试试这个

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

这将为您提供满足该条件的所有文件

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

如果您想要一份在其 responsaveis 数组中包含元素“daniela.morais@sofist.com.br”的文档,您可以消除项目运算符,例如

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

那会给你

{
    "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
}

希望能帮助到你

于 2015-04-17T17:37:57.503 回答