MongoDB JsonObject and JsonArray - mongodb

I'm new MongoDB.
I have a collection is named "surveyCollection".
I insert some data to collection with shell,
db.surveyCollection.insert({
"count":30,
"people": [
{
"firstName":"John",
"lastName":"Jason"
}
]
})
db.surveyCollection.insert({
"count":30,
"people": [
{
"firstName":"Sarah",
"lastName":"Smith"
}
]
})
And I have data below ( db.surveyCollection.find().pretty());
{
"_id" : ObjectId("5873d0c86c3319a579754d00"),
"count" : 30,
"people" : [
{
"firstName" : "John",
"lastName" : "Jason"
}
]
}
{
"_id" : ObjectId("5873d0c86c3319a579754d00"),
"count" : 30,
"people" : [
{
"firstName" : "Sarah",
"lastName" : "Smith"
}
]
}
I don't know how can I insert a new people to any survey. I mean, I want to have datas like below;
{
"_id" : ObjectId("5873d0c86c3319a579754d00"),
"count" : 30,
"people" : [
{
"firstName" : "John",
"lastName" : "Jason"
}
]
}
{
"_id" : ObjectId("5873d0c86c3319a579754d00"),
"count" : 30,
"people" : [
{
"firstName" : "Sarah",
"lastName" : "Smith"
},
{
"firstName" : "George",
"lastName" : "Smith"
}
]
}
I mean, how can I reach values in JsonArray?
Thank you

Use $push method to push an item into array of a document as shown below :
db.surveyCollection.update(
{ "_id" : ObjectId("5873d0c86c3319a579754d00") },
{ $push: { people: { "firstName" : "George", "lastName" : "Smith"} } }
)
This will add the object { "firstName" : "George", "lastName" : "Smith"} to the array people in the document of {"_id" : ObjectId("5873d0c86c3319a579754d00")}

Related

$lookup aggregation failed to display array value

I'm working with MongoDB and I've 2 collections.
data collection ["user-profile"]
{
"_id" : ObjectId("60650e6fc4b4603e1e78bb23"),
"firstName" : "Luthfan",
"lastName" : "Difiesa",
"mobile" : "86742633497",
"gender" : "male",
"createdOn" : ISODate("2021-04-22T05:26:07.428+0000"),
"updatedOn" : ISODate("2021-04-22T05:26:55.218+0000")
}
data collection ["user-wishlist"]
{
"_id" : ObjectId("60650e7a1a4a817a1dd0a29c"),
"userId" : "86742633497",
"contents" : [
{
"_id" : ObjectId("5ef9d2da228f840bbd41649c"),
"name" : "Kelas 11"
}
]
}
expected output:
{
"_id" : ObjectId("60650e6fc4b4603e1e78bb23"),
"firstName" : "Luthfan",
"lastName" : "Difiesa",
"mobile" : "86742633497",
"gender" : "male",
"contents" : [
{
"_id" : ObjectId("5ef9d2da228f840bbd41649c"),
"name" : "Kelas 11"
}
]
}
Here's the query:
db.getCollection("user-profile").aggregate(
[
{
"$lookup" : {
"from" : "user-wishlist",
"localField" : "mobile",
"foreignField" : "userId",
"as" : "contents"
}
}
],
{
"allowDiskUse" : false
}
);
But the result is like this:
{
"_id" : ObjectId("60650e6fc4b4603e1e78bb23"),
"firstName" : "Luthfan",
"lastName" : "Difiesa",
"mobile" : "86742633497",
"gender" : "male",
"contents" : [
]
}
is't because of collection name using special character or type data from foreign or localField? thank u...
Your query looks good, just need add a stage after lookup to achieve your desire result,
{
$addFields: {
contents: {
$arrayElemAt: ["$contents.contents", 0]
}
}
}
Playground

How to group nasted array in mongo db

In my mongodb collection I have next records
{ "_id" : ObjectId("5d0dfb68264b2d01a3237a3e"), "name" : "lexa", "cat" : 2, "gender" : "male", "date" : ISODate("2019-06-22T09:56:56.070Z") }
{ "_id" : ObjectId("5d0dfb6c264b2d01a3237a3f"), "name" : "dima", "cat" : 2, "gender" : "male", "date" : ISODate("2019-06-22T09:57:00.925Z") }
{ "_id" : ObjectId("5d0dfb75264b2d01a3237a40"), "name" : "lena", "cat" : 2, "gender" : "female", "date" : ISODate("2019-06-22T09:57:10.003Z") }
{ "_id" : ObjectId("5d0dfb7a264b2d01a3237a41"), "name" : "nina", "cat" : 2, "gender" : "female", "date" : ISODate("2019-06-22T09:57:14.941Z") }
{ "_id" : ObjectId("5d0dfb8f264b2d01a3237a42"), "name" : "nina", "cat" : 1, "gender" : "female", "date" : ISODate("2019-06-22T09:57:35.128Z") }
{ "_id" : ObjectId("5d0dfb93264b2d01a3237a43"), "name" : "lena", "cat" : 1, "gender" : "female", "date" : ISODate("2019-06-22T09:57:39.789Z") }
{ "_id" : ObjectId("5d0dfb9b264b2d01a3237a44"), "name" : "dima", "cat" : 1, "gender" : "male", "date" : ISODate("2019-06-22T09:57:47.150Z")
Then I use aggregation mongo framework to group that records by cat.
db.foo.aggregate([{'$group':
{
'_id': '$cat',
'users':
{'$push':
{
'name':'$name',
'gender': '$gender'
}
}
}
}])
That query returns me next result
{
"_id" : 1,
"users" : [
{
"name" : "nina",
"gender" : "female"
},
{
"name" : "lena",
"gender" : "female"
},
{
"name" : "dima",
"gender" : "male"
}
]
}
{
"_id" : 2,
"users" : [
{
"name" : "lexa",
"gender" : "male"
},
{
"name" : "dima",
"gender" : "male"
},
{
"name" : "lena",
"gender" : "female"
},
{
"name" : "nina",
"gender" : "female"
}
]
}
And the question is what I need to add to my query to group by my users array. I want to get something like this
{
"_id" : 1,
"users" : [
{
"gender": "male",
"names": ["dima"]
},
{
"gender": "female",
"names": ["lena", "nina"]
}
]
}
{
"_id" : 2,
"users" : [
{
"gender": "male",
"names": ["lexa", "dima"]
},
{
"gender": "female",
"names": ["lena", "nina"]
}
]
}
I need to have my nested array been grouped too without loosing first group result
Would be easier to first group by cat X gender and then restructure the data like so :
db.foo.aggregate([
{'$group':
{
'_id': {cat: '$cat', gender: "$gender"},
'names':
{'$push':
{
'name':'$name',
}
}
}
},
{
$group: {
'_id': "$_id.cat",
users: { $push: { gender: "$_id.gender", names: "$names" }
}
}
])

can we sort result of group() in mongoDB?

I have one scenario like need to sort the result of group() in mongoDB
For Example:
Suppose you have documents in Student collection like below
{
"id":"kjdkfdjkljflkd73847",
"DepartementID":123,
"parties":[
{
"idNumber" : "103",
"studentName" : {
"suffix" : "Mr",
"firstName" : "ram",
"middleName" : "",
"lastName" : "gorli"
}
},
{
"idNumber" : "99",
"studentName" : {
"suffix" : "Mr",
"firstName" : "ramesh",
"middleName" : "",
"lastName" : "vogue"
}
},
]
},
{
"id":"kjdkfdjkljflkd73847",
"DepartementID":123,
"parties":[
{
"idNumber" : "101",
"studentName" : {
"suffix" : "Mr",
"firstName" : "Mike",
"middleName" : "",
"lastName" : "john"
}
},
{
"idNumber" : "102",
"studentName" : {
"suffix" : "Mr",
"firstName" : "ram",
"middleName" : " ",
"lastName" : "gorli"
}
},
]
}
I'm grouping the details by using DepartmentID in student collection, In group() itself I need to sort by using last name in parties. how can we achieve this in one query it self?
please help me out. I really appreciate your efforts.
This will work for you :
db.getCollection('quotes').aggregate([
{
$unwind:"$parties"
},
{
$sort:{
"parties.studentName.lastName": 1
}
},
{
$group:{
_id:"$DepartementID",
parties:{
$push:"$parties"
}
}
}
])

Nested array count without unwind?

Is it possible to count a nested array without using $unwind in MongoDB? If possible then help me out. My json file is like this:
{
"_id" : ObjectId("57307906f051147d5317984e"),
"user" : [
{
"firstName" : "chetan",
"lastName" : "kumar",
"age" : 23,
"like" : [
{
"bookname" : "mongo"
},
{
"bookname" : "php"
},
{
"bookname" : "java"
}
]
},
{
"firstName" : "nepolean",
"lastName" : "dang",
"age" : 26,
"like" : [
{
"bookname" : "mongo"
},
{
"bookname" : "php"
}
]
},
{
"firstName" : "Raj",
"lastname" : "kumar",
"age" : 26,
"like" : [
{
"bookname" : "mongo"
}
]
}
],
"sales" : [
{
"firstName" : "ashu",
"lastName" : "jha",
"age" : 27
}
]
}
If I use $unwind then I can easily find out the result like this:
db.userdetail.aggregate([
{"$unwind": "$user"},
{"$project": {
"likecount": { "$size": "$user.like" }
}}
]).pretty()
{ "_id" : ObjectId("57307906f051147d5317984e"), "likecount" : 3 }
{ "_id" : ObjectId("57307906f051147d5317984e"), "likecount" : 2 }
{ "_id" : ObjectId("57307906f051147d5317984e"), "likecount" : 1 }

Ask update and delete multiple array in MongoDb

I have a real case in my project:
> db.foo.insert({a:'1',
... province: [{id:'1',name:'Yogyakarta',state:[{id:'1',name:'bantul'}]}]
... })
Then I find()...
> db.foo.find();
> { "_id" : ObjectId("5279ef4c6cfd9d5c0e19bbe0"),
"a" : "1",
"province" : [
{"id" : "1",
"name" : "Yogyakarta",
"state" : [
{"id" : "1","name" : "bantul" }
]
}
]
}
how to remove and update state with id='1'
REMOVE
To remove the documents that match a deletion criteria, call the remove() method with the <query> parameter.
db.foo.remove({'province.state.id': '1'})
Example
First, insert data Yogyakarta - Bantul
db.foo.insert({a:'1', province: [{id:'1',name:'Yogyakarta',state:[{id:'1',name:'bantul'}]}] })
Insert data Jakarta - Jakarta Selatan
db.foo.insert({a:'1', province: [{id:'2',name:'Jakarta',state:[{id:'2',name:'Jakarta Selatan'}]}] })
Now, you have two documents
db.foo.find();
Result
[
{ "a" : "1", "_id" : { "$oid" : "527b54c6cc937439340367f9" }, "province" : [ { "name" : "Yogyakarta", "id" : "1", "state" : [ { "name" : "bantul", "id" : "1" } ] } ] },
{ "a" : "1", "_id" : { "$oid" : "527b54d3cc937439340367fa" }, "province" : [ { "name" : "Jakarta", "id" : "2", "state" : [ { "name" : "Jakarta Selatan", "id" : "2" } ] } ] }
]
Now, delete document where the subdocument province contains a field state whose value 1.
db.foo.remove({'province.state.id': '1'})
Check
db.foo.find();
Now, you have one document
[
{ "a" : "1", "_id" : { "$oid" : "527b54d3cc937439340367fa" }, "province" : [ { "name" : "Jakarta", "id" : "2", "state" : [ { "name" : "Jakarta Selatan", "id" : "2" } ] } ] }
]
UPDATE
By default, the update() method updates a single document. If the multi option is set to true, the method updates all documents that match the query criteria.
db.foo.update({'province.state.id': '2'}, { $set: {'a': '2'} })
Check
db.foo.find();
Result
[
{ "a" : "2", "_id" : { "$oid" : "527b54d3cc937439340367fa" }, "province" : [ { "name" : "Jakarta", "id" : "2", "state" : [ { "name" : "Jakarta Selatan", "id" : "2" } ] } ] }
]