I got the below illustrated JSON in my MongoDB. I got several hundred entries. The issue is that a few of them have multiple entries within the embedded array. In this illustration the entry_2 and the following entry_2 object of the array type are not allowed. I want to delete one of the two objects where the name of type array is of value "entry_2".
{
"id": null,
"name": "",
"array" [
{
"name": "entry_1"
},
{
"name": "entry_2"
},
{
"name": "entry_2"
},
{
"name": "entry_3"
}
]
}
Hence, my JSON should look like the following after the Query:
{
"id": null,
"name": "",
"array" [
{
"name": "entry_1"
},
{
"name": "entry_2"
},
{
"name": "entry_3"
}
]
}
I tried to browse SO and read http://docs.mongodb.org/manual/tutorial/query-documents/#exact-match-on-the-embedded-document but I couldn't get a solution.
-- EDIT --
I have to use the option { allowDiskUse: true } and don't know how to implement it in the query. Furthermore, I tried to adjust the query to my certain use case, where I got the following structure:
{
"_id": {
"$oid": "556ccf6f59bbda5ea20a8884"
},
"id": 1159,
"description": "Cheese, goat, soft type",
"tags": [],
"manufacturer": "",
"group": "Dairy and Egg Products",
"portions": [
{
"unit": "oz",
"grams": 28.35,
"amount": 1
}
],
"nutrients": [
{
"description": "Protein",
"group": "Composition",
"value": 18.52,
"units": "g"
},
{
"group": "Composition",
"value": 21.08,
"units": "g",
"description": "Total lipid (fat)"
},
{
"description": "Protein",
"group": "Composition",
"value": 18.52,
"units": "g"
}
]
}
Based on the answer below I tried:
var pipeline = [
{
"$unwind": "$nutrients"
},
{
"$group": {
"_id": "$_id",
"id": { "$first": "$id" }
"description": { "$first": "$description" },
"tags" : { "$first": "$tags" },
"manufacturer" : { "$first": "$manufacturer" },
"group" : { "$first": "$group" },
"portions" : { "$first": "$portions" },
"nutrients": {
"$addToSet": "$nutrients"
}
}
}
],
options = { "allowDiskUse": true };
db.collection.aggregate(pipeline, options);
I get the error message: "unexpected String". I suppose it has something to do with the "_id" object an "tags" array.
,after the"id": { "$first": "$id" }expression in the$groupoperator expression.