2015-04-17 79 views
0

我想獲得數組中的特定元素並通過responsaveis.$[email protected]),但沒有結果,在我的語法中存在問題?如何在mongoDB中獲得數組的特定元素?

{ 
    "_id" : ObjectId("54fa059ce4b01b3e086c83e9"), 
    "agencia" : "Abc", 
    "instancia" : "dentsuaegis", 
    "cliente" : "Samsung", 
    "nomeCampanha" : "Serie A", 
    "ativa" : true, 
    "responsaveis" : [ 
     "[email protected]", 
     "[email protected]" 
    ], 
    "email" : "[email protected]" 
    } 

語法1

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

語法2

db.getCollection('validatag_campanhas').find({"responsaveis.$" : "[email protected]"}) 

結果

Fetched 0 record(s) in 1ms 

回答

1

$位置運算符僅用於更新(...)或項目調用,不能用它返回數組中的位置。

正確的語法是: -

語法1

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

語法2

db.getCollection('validatag_campanhas').find({"responsaveis" : "[email protected]"}) 

如果你只是想要表現的特定元素,你可以使用位置操作$在投影爲

{「responsaveis。$」:1}

db.getCollection('validatag_campanhas').find({"responsaveis" : "[email protected]"},{"responsaveis.$":1}) 
0

嘗試使用此

db.validatag_campanhas.aggregate(
    { $unwind : "$responsaveis" }, 
     { 
     $match : { 
     "responsaveis": "[email protected]" 
     } 
    }, 
    { $project : { responsaveis: 1, _id:0 }} 
); 

這將使你符合這條件

{ 
    "result" : [ 
     { 
      "responsaveis" : "[email protected]" 
     } 
    ], 
    "ok" : 1 
} 

如果您希望在其responsaveis數組元素一個文件「[email protected]」可以消除項目的所有文件像

db.validatag_campanhas.aggregate(
    { $unwind : "$responsaveis" }, 
     { 
     $match : { 
     "responsaveis": "[email protected]" 
     } 
    } 
); 

而且運營商,這將使你

{ 
    "result" : [ 
     { 
      "_id" : ObjectId("54fa059ce4b01b3e086c83e9"), 
      "agencia" : "Abc", 
      "instancia" : "dentsuaegis", 
      "cliente" : "Samsung", 
      "nomeCampanha" : "Serie A", 
      "ativa" : true, 
      "responsaveis" : "[email protected]", 
      "email" : "[email protected]" 
     } 
    ], 
    "ok" : 1 
} 

希望它可以幫助

相關問題