问题
I have imported a huge json file into mongoDB. It has imported as one whole document (with one _id). My json looks like this:
{
"_id": ObjectId("bas8adsfa832034821"),
"Spele": {
"Laiks": "2017/01/11",
"Skatitaji": 6740,
"Vieta": "Newlands Stadium",
"T": [
{
"Uzvards": "Antamo",
"Vards": "Dennis"
},
{
"Uzvards": "Prompa",
"Vards": "Pedro"
}
],
"Komanda": [
{
"Nosaukums": "Barcelona",
"Speletaji": {
"Speletajs": [
{
"Loma": "V",
"Nr": 16,
"Uzvards": "Sam",
"Vards": "Sidney"
},
{
"Loma": "A",
"Nr": 17,
"Uzvards": "Cisovsky",
"Vards": "Marian"
}
]
}
}
]
}
}
So with every query I try, it returns the whole document. Setting specific parameters don't help like: db.games.find({"Spele.Komanda.Speletaji.Speletajs.Nr" : 16})
When I'd expect it to return
{ "Loma" : "V",
"Nr" : 16,
"Uzvards" : "Sam"
"Vards" : ""Sidney"
}
But it returns the whole document instead. Maybe I'm not using the query right, or I have to provide every nested document with _id, but I don't know how. I can use mongo shell or PHP to do this.
回答1:
You can try below aggregation query.
$filter
inner array and $arrayElemAt
to project the matched element.
$map
to output all matching Speletajs elements across all Kamadas.
$arrayElemAt
to reduce to a single match. For multiple matches remove $arrayElemAt
.
db.games.aggregate([
{"$match":{"Spele.Komanda.Speletaji.Speletajs.Nr":16}},
{"$project":{
"Speletaji":{
"$arrayElemAt":[
{"$map":{
"input":"$Spele.Komanda",
"in":{
"$arrayElemAt":[
{"$filter":{
"input":"$$this.Speletaji.Speletajs",
"cond":{"$eq":["$$this.Nr",16]}
}},
0]
}
}},
0]
}
}}
])
回答2:
This is because you only specify the query part of the .find({})
operation and not the projection part. This is the syntax of the .find({})
:
db.collection.find({query}, {projection});
So your query should be more similar to something similar to:
db.games.find({"Spele.Komanda.Speletaji.Speletajs.Nr":16},{"Spele.Komanda.Speletaji.Speletajs":1});
However this will return more than what you want. To return preceiselly what you want you will need projection operators: https://docs.mongodb.com/manual/reference/operator/projection/
来源:https://stackoverflow.com/questions/48128835/how-to-query-a-deeply-nested-json-document