How to retrieve distinct keys inside an object in MongoDB - arrays

I have this in MongoDB:
{ "_id" : ObjectId("58fb35531eb5df245d5d434f"), "name" : "d1.html", "indexation" : { "Citroen" : 1, "color" : 1, "Marca" : 1, "rojo" : 1 } }
{ "_id" : ObjectId("58fb35531eb5df245d5d4350"), "name" : "d2.html", "indexation" : { "blancos" : 1, "ocasión" : 1, "Madrid" : 1, "Coches" : 1, "rojo" : 1, "coches" : 1 } }
{ "_id" : ObjectId("58fb35531eb5df245d5d4351"), "name" : "d3.html", "indexation" : { "rojos" : 1, "Ocasión" : 1, "marcas" : 1, "Madrid" : 1, "blancas" : 1, "autos" : 1, "de" : 1 } }
You can see an image containing the above:
And I would like to get the distinct keys inside the object "indexation" in each document.
The result I woul like to get is: ["Citroen", "color", "Marca", "rojo", "blancos", "ocasión", "Madrid", "Coches", "coches", "rojos", "Ocasión", "marcas", "blancas" "autos", "de"].
I'm trying with distinct ("indexation") but I get the whole indexation...
Could you explain to me what do I have to do to get what I want, please?

You can use new $objectToArrray in 3.4.4 version to convert all key & value pair into document arrays followed by $unwind & $group with $addToSet to get distinct keys
db.collection.aggregate([{$project: {indexation: {$objectToArray: "$indexation"}}}, {$unwind:"$indexation"}, {$group:{_id:null, keys:{$addToSet:"$indexation.k"}}}])
For lower version you've to update indexation to look like below and and use
db.collection.distinct("indexation.k")
{ "_id" : ObjectId("58fb35531eb5df245d5d434f"), "name" : "d1.html", "indexation" : [{ "k" : "Citroen", "v" : 1 }, { "k" : "Marca", "v" : 1 }]}

Related

Insert numbers into mongo-db collection

I am currently learning Mongo DB and trying to insert numbers into my "numbers" collection (in mongo command shell).
//This works :
db.numbers.insertMany([{"number":1},{"number":2}]);
//This doesn't
db.numbers.insertMany([1,2,3,4,5,6]);
(1) Does that mean that number is not a valid document or I am missing a very basic concept ?
(2) Why Mongo-db is not assigning Object-ID to numbers automatically in this case ?
//actual output from Mongoshell version 4.2.6 command line
> db.numbers.insertMany([{"number":1},{"number":2}]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5f79fa89d04cd9e2b3acbf03"),
ObjectId("5f79fa89d04cd9e2b3acbf04")
]
}
> db.numbers.find();
{ "_id" : ObjectId("5f79fa89d04cd9e2b3acbf03"), "number" : 1 }
{ "_id" : ObjectId("5f79fa89d04cd9e2b3acbf04"), "number" : 2 }
> db.numbers.insertOne({number:[1,2,3,4,5,6]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5f79fa9ed04cd9e2b3acbf05")
}
> db.numbers.find();
{ "_id" : ObjectId("5f79fa89d04cd9e2b3acbf03"), "number" : 1 }
{ "_id" : ObjectId("5f79fa89d04cd9e2b3acbf04"), "number" : 2 }
{ "_id" : ObjectId("5f79fa9ed04cd9e2b3acbf05"), "number" : [ 1, 2, 3, 4, 5, 6 ] }
>

Access MongoDB Array of Embedded Documents in PHP

Hi I'm trying to reach embedded document inside this array:
"_id" : 0,
"name" : "Sykes",
"orders" : [
{
"invoiceNumber" : 788,
"cart" : [
{
"item" : 0,
"pkgId" : 3,
"qty" : 10
}
]
},
{
"invoiceNumber" : 801,
"cart" : [
{
"item" : 1,
"pkgId" : 1,
"qty" : 8
}
]
}
I've tried this:
db.customer.find({_id:1},{'orders.invoiceNumber':1,_id:0}).pretty()
I need to convert this command to PHP. Any help please?

Update / create subdocument in array

I got a data like this in my User collection on my MongoDB database
{
"_id" : ObjectId("5890a9598c36d45435d521c7"),
"name" : "Test Testsson",
"email": "test#test.com,"
"tasks": [{
"_id" : ObjectId("5890a9598c36d45435d521ce"),
"sessionid" : 0,
"value" : 7,
"actions" : [
{
"taskid" : 17,
"time" : 0.85302734375,
"_id" : ObjectId("5890a9598c36d45435d521d6")
},
{
"taskid" : 5,
"time" : 1.39321899414063,
"_id" : ObjectId("5890a9598c36d45435d521d5")
}
]
}, {
"_id" : ObjectId("5890a9598c36d45435d521qw"),
"sessionid" : 1,
"value" : 7,
"actions" : [
{
"taskid" : 1,
"time" : 0.85302734375,
"_id" : ObjectId("5890a9598c36d45435d521zx")
},
{
"taskid" : 5,
"time" : 1.39321899414063,
"_id" : ObjectId("5890a9598c36d45435d521yt")
}
]
}
]
}
I post data to my node / mongoose application and I want to update the tasks array.
I do a POST to /api/user/task/5890a9598c36d45435d521c7
with Body:
{
"sessionid" : 2,
"value" : 12,
"actions" : [
{
"taskid" : 4,
"time" : 0.85302734375,
"_id" : ObjectId("5890a9598c36d45435d521zx")
},
{
"taskid" : 9,
"time" : 1.39321899414063,
"_id" : ObjectId("5890a9598c36d45435d521yt")
}
]
}
I can find my tasks with this query:
User.findOne({
_id: ObjectId('58909be40c50e2d0345e916e'),
"tasks.sessionid": 0},
function(...){/* blah blah */});
But how do I update the data in the tasks array?
If the sessionid exists I want to update the subdocument with the
request body (given that the User exists)
If the sessionid DONT exist I want to create a new object from the
request body in the tasks array (given that the User exists)
If the ObjectId of the User in the url parameter DONT exist send http
status: 500
I tried with update and findAndModify but cant get it to work as expected. Anyone got any idees how to do this.

Adding item to an array in Typescript

I am working in TypeScript with MongoDB and I am trying to add an item to an array.
registeredUsers.update({ guid: ObjectId(req.cookies._id) }, {
$addToSet: {
favorites: [comicID]
}
});
This is the code I have currently, and I am trying to add the comicID to an array called favorites that is in registeredUsers. At the moment it does not seem to be adding to the array at all, so when I try to look at the array it is empty.
Your code seems fine. I suspect the reason you are not getting updates is because your search condition is not matching any documents.
Have you tried the following statement:
db.registeredUsers.find({ guid: ObjectId(req.cookies._id) })
If your search condition is valid, you should get the "desired" document back.
Here are my examples:
First create a doc.
> db.registeredUsers.insert({ "mycustom_id":1, "favorites":[1,2,3]})
WriteResult({ "nInserted" : 1 })
Check to see if the doc looks right.
> db.registeredUsers.find()
{ "_id" : ObjectId("56f88aa1d14e4832a027f625"), "mycustom_id" : 1, "favorites" : [ 1, 2, 3 ] }
Do an update based on one of the columns that I defined.
> db.registeredUsers.update({"mycustom_id" : 1}, { $addToSet: { favorites: 5}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Check the update results:
> db.registeredUsers.find()
{ "_id" : ObjectId("56f88aa1d14e4832a027f625"), "mycustom_id" : 1, "favorites" : [ 1, 2, 3, 5 ] }
Now, do an update based on the "_id" field.
> db.registeredUsers.update({"_id": ObjectId("56f88aa1d14e4832a027f625") }, { $addToSet: { favorites: 6}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Checking the result:
> db.registeredUsers.find()
{ "_id" : ObjectId("56f88aa1d14e4832a027f625"), "mycustom_id" : 1, "favorites" : [ 1, 2, 3, 5, 6 ] }
Another example where the update is expected to create the array:
> db.registeredUsers.insert({"a": 1})
WriteResult({ "nInserted" : 1 })
> db.registeredUsers.find()
{ "_id" : ObjectId("56f88aa1d14e4832a027f625"), "mycustom_id" : 1, "favorites" : [ 1, 2, 3, 5, 6 ] }
{ "_id" : ObjectId("56f88be6d14e4832a027f626"), "a" : 1 }
Updating based on "_id" again in a situation where the array favorites does not exist prior to the update
> db.registeredUsers.update({"_id" : ObjectId("56f88be6d14e4832a027f626")}, { $addToSet: { favorites: 6}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Check the results:
> db.registeredUsers.find()
{ "_id" : ObjectId("56f88aa1d14e4832a027f625"), "mycustom_id" : 1, "favorites" : [ 1, 2, 3, 5, 6 ] }
{ "_id" : ObjectId("56f88be6d14e4832a027f626"), "a" : 1, "favorites" : [ 6 ] }
As you can see my queries are identical to yours. You are comparing "guid" and I am comparing "_id". I am suspicious that "guid" does not contain what you expect it to contain, which leads to your "search condition" to the update to return 0 documents, consequently

Mongodb Java add new array element in document

I'm using mongo 2.2.3 and the java driver. My dilemma, I have to $push a field and value into an array element, but I cant seem to figure out how to do this. A sample of my data:
"_id" : 1,
"scores" : [
{
"type" : "english",
"score" : 78.97979
},
{
"type" : "spanish",
"score" : 6.99
}
]
I want to push one array attribute ("grade" : "A") in document where type = english.
after push document look like this :
"_id" : 1,
"scores" : [
{
"type" : "english",
"score" : 78.97979,
"grade" : "A"
},
{
"type" : "spanish",
"score" : 6.99
}
]
I tried using shell :
db.Sample.update({"scores.type" : "english"},{"$push" : {"scores": {"grade":"A"}}})
But this is not adding attribute on specific position.
Try this update with Set and reference:
db.Sample.update({"scores.type" : "english"},{"$set" : {"scores.$.grade":"A"}})

Resources