Mongodb: 请求JSON对象附加到数组

我完全是新的 mongodb, 现在有一件事我现在无法解决:

让我们想象一下你有以下文件 /简化/:


{
'someKey': 'someValue',
'array' : [
{'name' : 'test1',
'value': 'value1'
},
{'name' : 'test2',
'value': 'value2'
}
]
}


哪个查询将返回值相等的JSON对象 'value2'?

这意味着我需要这个json对象:


{
'name' : 'test2',
'value': 'value2'
}


当然,我已经尝试过许多可能的请求,但是它们都不是返回所需的要求


db.test.find/{'array.value':'value2'}/
db.test.find/{'array.value':'value2'}, {'array.value':1}/
db.test.find/{'array.value':'value2'}, {'array.value':'value2'}/


任何人都可以帮助并告诉我我做错了什么吗?

谢!
已邀请:

小明明

赞同来自:

使用位置操作员


db.test.find/
{ "array.value": "value2" },
{ "array.$": 1, _id : 0 }
/


出口


{ "array" : [ { "name" : "test2", "value" : "value2" } ] }


使用聚合


db.test.aggregate/[
{ $unwind : "$array"},
{ $match : {"array.value" : "value2"}},
{ $project : { _id : 0, array : 1}}
]/


出口


{ "array" : { "name" : "test2", "value" : "value2" } }


使用驾驶员

Java


MongoClient mongoClient = new MongoClient/new ServerAddress/"localhost", 27017//;
DB db = mongoClient.getDB/"mydb"/;
DBCollection collection = db.getCollection/"test"/;

DBObject unwind = new BasicDBObject/"$unwind", "$array"/;
DBObject match = new BasicDBObject/"$match", new BasicDBObject/
"array.value", "value2"//;
DBObject project = new BasicDBObject/"$project", new BasicDBObject/
"_id", 0/.append/"array", 1//;

List<dbobject> pipeline = Arrays.asList/unwind, match, project/;
AggregationOutput output = collection.aggregate/pipeline/;

Iterable<dbobject> results = output.results//;

for /DBObject result : results/ {
System.out.println/result.get/"array"//;
}


出口


{ "name" : "test2" , "value" : "value2"}


</dbobject></dbobject>

詹大官人

赞同来自:

尝试使用操作员 $in 通过以下方式:


db.test.find/{"array.value" : { $in : ["value2"]}}/

小明明

赞同来自:

您可以在元素中传输多个搜索对象。 match 准确的答案。


db.test.find/{'array':{$elemMatch:{value:"value2"}}/

output: {'name' : 'test1','value': 'value1'}

郭文康

赞同来自:

使用

$elemMatch

和 dot /./, 获得必要的结论


db.getCollection/'mobiledashboards'/.find/{"_id": ObjectId/"58c7da2adaa8d031ea699fff"/ },{ viewData: { $elemMatch : { "widgetData.widget.title" : "England" }}}/

要回复问题请先登录注册