How can I gather all fields with their values except five of them and put them inside new field in the same collection with mongoDB - mongodb

I have a collection that have many documents with too many fields but I want to gather many of these fields inside new field called Data, here is an example
{
"_id" : ObjectId("***********"),
"name" : "1234567890",
"mobile" : "Test",
.
.
.
.
.
etc
}
I want to use updateMany to make all the documents in the collection looks like this
{
"_id" : ObjectId("***********"),
"name" : "1234567890",
"mobile" : "Test",
"Data":{
.
.
.
.
.
etc
}
}

Option 1(few nested fields): You can do it following way:
db.collection.update({},
[
{
$project: {
data: {
name: "$name",
mobile: "$mobile"
}
}
}
],
{
multi: true
})
playground1
Option 2: (If the fields that need to be nested are too many):
db.collection.update({},
[
{
$project: {
data: "$$ROOT",
name: 1,
mobile: 1
}
},
{
$unset: [
"data.name",
"data.mobile"
]
}
],
{
multi: true
})
playground2

Related

Overwrite value and create key while update query in mongodb

I have a mongodb collection that looks like this:
{
"_id" : ObjectId("60471bd482c0da3c0e70d26f"),
"owner" : "John",
"propAvailable" : {
"val1" : true
}
},
{
"_id" : ObjectId("60471bd482c0da3c0e76523f"),
"owner" : "Matt",
"propAvailable" : {
"val1" : {
"val2" : true
}
}
I need to run an update query on this collection that will update the value of the 'propAvailable' key such that
db.collection('props').update({'owner' : 'John'} , {$set : {'propAvailable.val1.val2' : true}});
This query works if the document already looks like the second one but gives the error:
Cannot create field 'val2' in element {'val1': true} if the document format is the first one. Is there a way to write this query so that it overwrites the boolean 'true' and replaces it with the object {'val2' : true}
You can use:
db.collection.update({
"owner": "John"
},
{
$set: {
"propAvailable.val1": {
val2: true
}
}
})
To create val2: true inside propAvailable.val1 and replace its current content.
As you can see working on the playground
If you're using Mongo version 4.2+ you can use pipelined updates to achieve this, like so:
db.collection.updateMany({
owner: "John"
},
[
{
$set: {
"propAvailable.val1": {
$mergeObjects: [
{
$cond: [
{
$eq: [
"object",
{
$type: "$propAvailable.val1"
}
]
},
"$propAvailable.val1",
{}
]
},
{
val2: true
}
]
}
}
},
])
Mongo Playground
For older mongo versions this is impossible to do in 1 query if objects potentially have additional fields under val1 you want to preserve. You will have to either read and update, or execute two different updates for each case.

How would I push an object to this nested file in mongodb

My file has the following structure and I want to pass an object into the responses array, but it needs to go into the right comment responses array based on the post _id matching and then the comment_id matching.
{
post1: {
post: 'anything',
comments: [
{comment: 'anything', comment_id: RANDOM ID, responses: []},
{comment: 'something else', comment_id: ANOTHER RANDOM ID, responses: []},
],
_id: RANDOM ID
}
}
How would I add this object to the mongodb database, to add comments I used
Post.findOneAndUpdate({_id: req.body.post}, {$push: {comments: newComment}})
But I'm not sure how this works for adding responses because there's essentially 2 layers that need to be authenticated before it's pushed to the array
Try this,
Post.findOneAndUpdate({_id: req.body.post, 'comments.comment_id': req.body.commentId}, {$push: { comments: newComment}})
Considering this data:
{
"_id" : "abc",
"post1" : {
"_id" : "post_1",
"post" : "anything",
"comments" : [
{
"comment" : "anything",
"comment_id" : "comment_1",
"responses" : []
},
{
"comment" : "something else",
"comment_id" : "comment_2",
"responses" : []
}
]
}
}
The correct way to do it is like this:
Post.findOneAndUpdate(
{
_id: 'abc',
'post1._id': 'post_1',
'post1.comments.comment_id': 'comment_1',
},
{ $push: { 'post1.comments.$.responses': 'bla' } }
)
Note the $ in the path of the update query which is selected by { 'post1.comments.comment_id': 'comment_1' } in your conditional query.

MongoDB How to remove value from array if exist otherwise add

I have document
{
"_id" : ObjectId("5aebf141a805cd28433c414c"),
"forumId" : ObjectId("5ae9f82989f7834df037cc90"),
"userName" : "Name",
"usersLike" : [
"1","2"
],
"comment" : "Comment",
}
I want to remove value from usersLike array if the value exists, or add if the value does not exist.
Eg:
If I try to push 1 into usersLike, it should return
{
"_id" : ObjectId("5aebf141a805cd28433c414c"),
"forumId" : ObjectId("5ae9f82989f7834df037cc90"),
"userName" : "Name",
"usersLike" : [
"2"
],
"comment" : "Comment",
}
How can I query it..??
MongoDB version 4.2+ introduces pipelined update. Which means we can now use aggregation operators while updating. this gives us a lot of power.
db.collection.updateOne(
{
_id: ObjectId("597afd8200758504d314b534")
},
[
{
$set: {
usersLike: {
$cond: [
{
$in: ["1", "$usersLike"]
},
{
$setDifference: ["$usersLike", ["1"]]
},
{
$concatArrays: ["$usersLike", ["1"]]
}
]
}
}
}
]
)
Mongodb doesn't support conditional push or pull update. However you can still do it by using find:
db.collectionName.find({_id:ObjectId("597afd8200758504d314b534"),usersLike:{$in:["1"]}}).pretty()
if id exist in usersLike than pull else push.
Or you use the update query to pull as:
db.collectionName.update({
_id: ObjectId("597afd8200758504d314b534"),
usersLike: {
$in: ["1"]
}
}, {
$pull: { 'usersLike': "1" }
}, { multi: true })
And to push you can use:
db.collectionName.update({
_id:ObjectId("597afd8200758504d314b534"),
usersLike:{$nin:["1"]
}},{
$push:{'usersLike':"1"}
}, {multi: true})
Try this :
db.collectionName.update({_id:ObjectId("597afd8200758504d314b534")},{$pull:{'usersLike':"1"}}, {multi: true})
Try this
if db.collectionName.find({'_id':ObjectId("5aebf141a805cd28433c414c"),'usersLike:{'$in:['1']}}).count() > 0:
db.collectionName.update({'_id':ObjectId("5aebf141a805cd28433c414c")},{'$pull':{'usersLike':'1'}})
else:
db.collectionName.update({'_id':ObjectId("5aebf141a805cd28433c414c")},{'$addToSet':{'usersLike':'1'}})

Project values of different columns into one field

{
"_id" : ObjectId("5ae84dd87f5b72618ba7a669"),
"main_sub" : "MATHS",
"reporting" : [
{
"teacher" : "ABC"
}
],
"subs" : [
{
"sub" : "GEOMETRIC",
"teacher" : "XYZ",
}
]
}
{
"_id" : ObjectId("5ae84dd87f5b72618ba7a669"),
"main_sub" : "SOCIAL SCIENCE",
"reporting" : [
{
"teacher" : "XYZ"
}
],
"subs" : [
{
"sub" : "CIVIL",
"teacher" : "ABC",
}
]
}
I have simplified the structure of the documents that i have.
The basic structure is that I have a parent subject with an array of reporting teachers and an array of sub-subjects(each having a teacher)
I now want to extract all the subject(parent/sub-subjects) along with the condition if they are sub-subjects or not which are taught by a particular teacher.
For eg:
for teacher ABC i want the following structure:
[{'subject':'MATHS', 'is_parent':'True'}, {'subject':'CIVIL', 'is_parent':'FALSE'}]
-- What is the most efficient query possible ..? I have tried $project with $cond and $switch but in both the cases I have had to repeat the conditional statement for 'subject' and 'is_parent'
-- Is it advised to do the computation in a query or should I get the data dump and then modify the structure in the server code? AS in, I could $unwind and get a mapping of the parent subjects with each sub-subject and then do a for loop.
I have tried
db.collection.aggregate(
{$unwind:'$reporting'},
{$project:{
'result':{$cond:[
{$eq:['ABC', '$reporting.teacher']},
"$main_sub",
"$subs.sub"]}
}}
)
then I realised that even if i transform the else part into another query for the sub-subjects I will have to write the exact same thing for the property of is_parent
You have 2 arrays, so you need to unwind both - the reporting and the subs.
After that stage each document will have at most 1 parent teacher-subj and at most 1 sub teacher-subj pairs.
You need to unwind them again to have a single teacher-subj per document, and it's where you define whether it is parent or not.
Then you can group by teacher. No need for $conds, $filters, or $facets. E.g.:
db.collection.aggregate([
{ $unwind: "$reporting" },
{ $unwind: "$subs" },
{ $project: {
teachers: [
{ teacher: "$reporting.teacher", sub: "$main_sub", is_parent: true },
{ teacher: "$subs.teacher", sub: "$subs.sub", is_parent: false }
]
} },
{ $unwind: "$teachers" },
{ $group: {
_id: "$teachers.teacher",
subs: { $push: {
subject: "$teachers.sub",
is_parent: "$teachers.is_parent"
} }
} }
])

way to update multiple documents with different values

I have the following documents:
[{
"_id":1,
"name":"john",
"position":1
},
{"_id":2,
"name":"bob",
"position":2
},
{"_id":3,
"name":"tom",
"position":3
}]
In the UI a user can change position of items(eg moving Bob to first position, john gets position 2, tom - position 3).
Is there any way to update all positions in all documents at once?
You can not update two documents at once with a MongoDB query. You will always have to do that in two queries. You can of course set a value of a field to the same value, or increment with the same number, but you can not do two distinct updates in MongoDB with the same query.
You can use db.collection.bulkWrite() to perform multiple operations in bulk. It has been available since 3.2.
It is possible to perform operations out of order to increase performance.
From mongodb 4.2 you can do using pipeline in update using $set operator
there are many ways possible now due to many operators in aggregation pipeline though I am providing one of them
exports.updateDisplayOrder = async keyValPairArr => {
try {
let data = await ContestModel.collection.update(
{ _id: { $in: keyValPairArr.map(o => o.id) } },
[{
$set: {
displayOrder: {
$let: {
vars: { obj: { $arrayElemAt: [{ $filter: { input: keyValPairArr, as: "kvpa", cond: { $eq: ["$$kvpa.id", "$_id"] } } }, 0] } },
in:"$$obj.displayOrder"
}
}
}
}],
{ runValidators: true, multi: true }
)
return data;
} catch (error) {
throw error;
}
}
example key val pair is: [{"id":"5e7643d436963c21f14582ee","displayOrder":9}, {"id":"5e7643e736963c21f14582ef","displayOrder":4}]
Since MongoDB 4.2 update can accept aggregation pipeline as second argument, allowing modification of multiple documents based on their data.
See https://docs.mongodb.com/manual/reference/method/db.collection.update/#modify-a-field-using-the-values-of-the-other-fields-in-the-document
Excerpt from documentation:
Modify a Field Using the Values of the Other Fields in the Document
Create a members collection with the following documents:
db.members.insertMany([
{ "_id" : 1, "member" : "abc123", "status" : "A", "points" : 2, "misc1" : "note to self: confirm status", "misc2" : "Need to activate", "lastUpdate" : ISODate("2019-01-01T00:00:00Z") },
{ "_id" : 2, "member" : "xyz123", "status" : "A", "points" : 60, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment", "lastUpdate" : ISODate("2019-01-01T00:00:00Z") }
])
Assume that instead of separate misc1 and misc2 fields, you want to gather these into a new comments field. The following update operation uses an aggregation pipeline to:
add the new comments field and set the lastUpdate field.
remove the misc1 and misc2 fields for all documents in the collection.
db.members.update(
{ },
[
{ $set: { status: "Modified", comments: [ "$misc1", "$misc2" ], lastUpdate: "$$NOW" } },
{ $unset: [ "misc1", "misc2" ] }
],
{ multi: true }
)
Suppose after updating your position your array will looks like
const objectToUpdate = [{
"_id":1,
"name":"john",
"position":2
},
{
"_id":2,
"name":"bob",
"position":1
},
{
"_id":3,
"name":"tom",
"position":3
}].map( eachObj => {
return {
updateOne: {
filter: { _id: eachObj._id },
update: { name: eachObj.name, position: eachObj.position }
}
}
})
YourModelName.bulkWrite(objectToUpdate,
{ ordered: false }
).then((result) => {
console.log(result);
}).catch(err=>{
console.log(err.result.result.writeErrors[0].err.op.q);
})
It will update all position with different value.
Note : I have used here ordered : false for better performance.