Update array with multiple conditions in mongodb - node.js

I have this document:
{
"_id" : ObjectId("5b673f525ef92ec6ef16504e"),
"events" : [
{
"name" : "Winner",
"map" : 0,
"something" : []
},
{
"name" : "Winner",
"map" : 2,
"something" : []
},
{
"name" : "DifferentName",
"map" : 2,
"something" : []
}
]
}
If I run the following update:
db.getCollection('test').updateOne({
"_id": ObjectId("5b673f525ef92ec6ef16504e"),
"events.name": "Winner",
"events.map": 2
},
{$push: {
"events.$.something": {
something: "test",
}
}
})
I get the bad result:
{
"_id" : ObjectId("5b673f525ef92ec6ef16504e"),
"events" : [
{
"name" : "Winner",
"map" : 0,
"something" : [
{
"something" : "test"
}
]
},
{
"name" : "Winner",
"map" : 2,
"something" : []
},
{
"name" : "DifferentName",
"map" : 2,
"something" : []
}
]
}
This is wrong, because "something" : "test" should be in the second element, where the map is equal to 2.
If I change the field "name" to "a" and run the same update, then I get the right result:
{
"_id" : ObjectId("5b673f525ef92ec6ef16504e"),
"events" : [
{
"a" : "Winner",
"map" : 0,
"something" : []
},
{
"a" : "Winner",
"map" : 2,
"something" : [
{
"something" : "test"
}
]
},
{
"a" : "DifferentName",
"map" : 2,
"something" : []
}
]
}
Now you can see, that "something" : "test" is in the right place (second event). Is this because I have used "name" and "name" is some kind of reserved keyword in Mongo?

When there are multiple conditions to match inside an array then the .Dot notation doesn't work with update query.
You need to use $elemMatch to match exact two fields inside an array
db.getCollection('test').updateOne(
{
"_id": ObjectId("5b673f525ef92ec6ef16504e"),
"events": { "$elemMatch": { "name": "Winner", "map": 2 }}
},
{
"$push": { "events.$.something": { "something": "test" }}
}
)

Related

mongo : update property of specific element in array

I have this collection :
{
"_id" : ObjectId("5ac69e90a9d1a5f3e01a5233"),
"category": "spain",
"products" : [
{
"label" : "uno"
},
{
"label" : "dos"
},
{
"label" : "tres"
}
]
},
{
"_id" : ObjectId("5ac69e90a9d1a5f3e01a5234"),
"category": "england",
"products" : [
{
"label" : "one"
},
{
"label" : "two"
},
{
"label" : "three"
}
]
}
I want to do the following operation : update the label from "one" to "four" of the object with the category england. But I have some troubles to design the most elegant and performant solution :
first solution : I could copy paste and rewrite the entire document with just replacing the one by four
second solution where I struggle : I would like to find the element with label equals to one and updates it to four, but I don't know how to do. I don't want to use mongo path index like 'products.O.label' because I can't garantee that the product with label one will be at position 0 in the products array.
Thanks in advance
You could use this one:
db.collection.updateMany(
{ category: "england" },
{ $set: { "products.$[element].label": "four" } },
{ arrayFilters: [{ "element.label": "one" }] }
)
If you prefer and aggregation pipeline it would be this one:
db.collection.updateMany(
{ category: "england" },
[{
$set: {
products: {
$map: {
input: "$products",
in: {
$cond: {
if: { $eq: ["$$this.label", "one"] },
then: { label: "four" },
else: "$$this"
}
}
}
}
}
}]
)
but it might be an overkill, in my opinion.
Further, referring to #Wernfried Domscheit, another way using aggregation.
> db.catg1.find();
{ "_id" : ObjectId("5ac69e90a9d1a5f3e01a5233"), "category" : "spain", "products" : [ { "label" : "uno" }, { "label" : "dos" }, { "label" : "tres" } ] }
{ "_id" : ObjectId("5ac69e90a9d1a5f3e01a5234"), "category" : "england", "products" : [ { "label" : "four" }, { "label" : "two two" }, { "label" : "three" } ] }
> db.catg1.aggregate([
... {$unwind:"$products"},
... {$match:{category:"england",
... "products.label":"four"
... }
... },
... ]).forEach(function(doc){
... print(doc._id);
... db.catg1.update(
... {"_id":doc._id},
... { $set:{"products.$[element].label":"one"}},
... {arrayFilters: [{"element.label":"four"}]}
... );
... });
ObjectId("5ac69e90a9d1a5f3e01a5234")
> db.catg1.find();
{ "_id" : ObjectId("5ac69e90a9d1a5f3e01a5233"), "category" : "spain", "products" : [ { "label" : "uno" }, { "label" : "dos" }, { "label" : "tres" } ] }
{ "_id" : ObjectId("5ac69e90a9d1a5f3e01a5234"), "category" : "england", "products" : [ { "label" : "one" }, { "label" : "two two" }, { "label" : "three" } ] }
> db.version();
4.2.6
>

Mongo: filter documents from multiple collections and merge

I am new to mongo and NodeJS and have a use case where I want to get filtered results from multiple collection.
Advance apologies for the long post.
for ex:
collectionA
{
"_id" : "foo#gmail.com",
"name" : "Foo",
"location" : {
"coordinates" : [
-122.420170,
37.780080
],
"type" : "Point"
}
},
{
"_id" : "bar#gmail.com,
"name" : "Bar",
"location" : {
"coordinates" : [
-122.420060,
37.780180
],
"type" : "Point"
}
}
collectionB: Some attributes are not present for all the documents and hence optional
{
"_id" : "foo#gmail.com"
"AttributeA" : [
{
"name" : "AttA_Name",
"val" : "Coll_B_AttA_Val_Foo"
},
{
"name" : "AttA_Name1",
"val" : "Coll_B_AttA_Val_Foo"
}]
},
{
"_id" : "bar#gmail.com"
"AttributeA" : [
{
"name" : "AttA_Name",
"val" : "Coll_B_AttA_Val_Bar"
},
{
"name" : "AttA_Name2",
"val" : "Coll_B_AttA_Val_Bar"
}
],
"AttributeB" : [
{
"name" : "AttB_Name",
"val" : "Coll_B_AttB_Val_Bar"
}
]
}
CollectionC: Some attributes are not present for all the documents and hence optional
{
"_id" : "foo#gmail.com"
"AttributeA" : [
{
"name" : "Coll_C_AttA_Name",
"val" : "Coll_C_AttA_Val_Foo"
}]
},
{
"_id" : "bar#gmail.com"
"AttributeA" : [
{
"name" : "Coll_C_AttA_Name",
"val" : "Coll_C_AttA_Val_Bar"
}
],
"AttributeB" : [
{
"name" : "Coll_C_AttB_Name",
"val" : "Coll_C_AttB_Val_Bar"
}
]
}
I know Collection B and C schema looks the same but the purpose is different and they have to be different. DB design is not the question so I would appreciate if do not put all the focus on it.
Query:
Assume there is another user (Alan) with same attributes present as Bar that exist in the collection but is not living nearby the location of Bar.
The query I am trying to build on top of these is,
Find people living nearby from CollectionA
And Collection B, if AttributeA exist and have an element with name: AttA_Name
And in Collection C, if AttributeA exist and have an name: Coll_C_AttA_Name
In the above case I am expecting a result as
{
"_id" : "foo#gmail.com",
"name" : "Foo",
"location" : {
"coordinates" : [
-122.420170,
37.780080
],
"type" : "Point"
},
"collectionB_AttributeA" : [
{
"name" : "AttA_Name",
"val" : "Coll_B_AttA_Val_Foo"
},
{
"name" : "AttA_Name1",
"val" : "Coll_B_AttA_Val_Foo"
}]
,
"collectionC_AttributeA" : [
{
"name" : "Coll_C_AttA_Name",
"val" : "Coll_C_AttA_Val_Foo"
}]
},
{
"_id" : "bar#gmail.com,
"name" : "Bar",
"location" : {
"coordinates" : [
-122.420060,
37.780180
],
"type" : "Point"
},
"collectionB_AttributeA":[
{
"name" : "AttA_Name",
"val" : "Coll_B_AttA_Val_Bar"
},
{
"name" : "AttA_Name2",
"val" : "Coll_B_AttA_Val_Bar"
}
],
"collectionC_AttributeA":[
{
"name" : "Coll_C_AttA_Name",
"val" : "Coll_C_AttA_Val_Bar"
}
]
}
There is one way of doing is in parts:
query Collection A and get the nearby people
Loop through the result of 1 and find in CollectionB if they have AttributeA and an element with name AttA_Name and eliminate if they don't match.
Loop through the filtered results from 2 and find in CollectionC if they have AttributeA and and element with name Coll_C_AttA_Name and if they don't eliminate such documents.
Is there a way I can use aggregate to build this query as one? I tried reading and trying the aggregate but seems like my understanding is incomplete.
let result = await CollectionASchema.aggregate([
{
$geoNear: {
near: { type: "Point", coordinates: [ Number(long) , Number(lat) ] },
distanceField: "dist.calculated",
minDistance: 0,
maxDistance: radiusinmetres,
spherical: true
}
},
{
$lookup:
{
from: 'collectionB',
pipeline: [
{ $match : { $and: [{ AttributeA :{$exists: true}}, { [category]: { $elemMatch: { name: “AttA_Name” } } }] }},
{ $project: { AttributeA: 0 } }
],
as: "collectionB_AttributeA"
}
}
])
If you can explain if this is possible or let me know off this is the right approach that would be helpful.

How to push new field in array mongodb

Imagine I have database like
{
"_id" : ObjectId("594994d1ab6c161168aa5969"),
"user_id" : ObjectId("594994d1ab6c161168aa5968"),
"active" : [
{
"type" : "active"
},
{
"type" : "inactive"
}
]
}
I want add to first object in active array . Here is result I expected
{
"_id" : ObjectId("594994d1ab6c161168aa5969"),
"user_id" : ObjectId("594994d1ab6c161168aa5968"),
"active" : [
{
"type" : "active",
"note": [{
content: 'here is content',
title : ' here is title'
}]
},
{
"type" : "inactive"
}
]
}
Here is code I tried
db.collection('..').update({'user_id' : ObjectId(userId)} ,
{$push:{ "active.0": "note": [{
content: 'here is content',
title : ' here is title'
}] } )
But I get The field 'active.0' must be an array but is of type object in document . Where is my wrong ? Please help
Starting with your document like this:
{
"_id" : ObjectId("594994d1ab6c161168aa5969"),
"user_id" : ObjectId("594994d1ab6c161168aa5968"),
"active" : [
{
"type" : "active"
},
{
"type" : "inactive"
}
]
}
You run the $push like this:
db.collection.update(
{ "_id" : ObjectId("594994d1ab6c161168aa5969") },
{ "$push":{ "active.0.note": { content: 'here is content', title : ' here is title' } } }
)
Which creates the new array within the first element like so:
{
"_id" : ObjectId("594994d1ab6c161168aa5969"),
"user_id" : ObjectId("594994d1ab6c161168aa5968"),
"active" : [
{
"type" : "active",
"note" : [
{
"content" : "here is content",
"title" : " here is title"
}
]
},
{
"type" : "inactive"
}
]
}
Everything here is cut and paste from my shell.

MongoDB update $pull document from multiple arrays

I have a document with the following structure (simplified):
{
"containers": [
{
"containerId": 1,
"components": ["component1", "component2"]
},
{
"containerId": 2,
"components": ["component3", "component1"]
}]
}
How would one write a query that removes "component1" from BOTH containers? Is this possible?
So far I've tried doing {"$pullAll": { "containers.$.component": ["component1"]}}, a similar query with $pull, setting multi: true but I always end up removing the component from the first array only (I'm using .update())
EDIT: Raw data ahead!
{
"_id" : ObjectId("53a056cebe56154c99dc950b"),
"_embedded" : {
"click" : {
"items" : [],
"_links" : {
"self" : {
"href" : "http://localhost/v1/click"
}
}
},
"container" : {
"_links" : {
"self" : {
"href" : "http://localhost/v1/container"
}
},
"items" : [
{
"name" : "Container test",
"uriName" : "Container_test",
"description" : "this is a test container",
"containerId" : "CONTAINER TEST+SITE_TEST",
"component" : [
"ANOTHER COMPONENT+SITE_TEST",
"ANOTHER COMPONENT+SITE_TEST",
"SARASA+SITE_TEST"
],
"_links" : {
"self" : {
"href" : "http://localhost/v1/container/CONTAINER TEST+SITE_TEST"
}
}
},
{
"name" : "sasasa",
"uriName" : "sasasa",
"description" : "container description",
"containerId" : "SASASA+SITE_TEST",
"component" : [
"ANOTHER COMPONENT+SITE_TEST",
"COMPONENT+SITE_TEST",
"FAFAFA+SITE_TEST",
"SARASA+SITE_TEST"
],
"_links" : {
"self" : {
"href" : "/v1/container/SASASA+SITE_TEST"
}
}
}
]
}
},
"name" : "SITE_TEST",
"siteId" : "SITE_TEST",
"url" : "/v1/site"
}
Ok, so what I'm trying to do is remove the component "SARASA+SITE_TEST" from the two containers. I'm using robomongo to test the queries. I've tried db.site.update({"_embedded.container.items.component": "SARASA+SITE_TEST"},{"$pullAll": { "_embedded.container.items.component": ["SARASA+SITE_TEST"]}}, {multi: true}) and it didn't work, previously I've tried db.site.update({"_embedded.container.items.component": "SARASA+SITE_TEST"},{"$pull": { "_embedded.container.items.$.component": "SARASA+SITE_TEST"}}, {"multi": true}) and it didn't work either. I assume robomongo exposes the mongo driver directly, I didn't try to run this from the command line.
(the document is a "site", that's why my queries start with db.site)
I had a similar problem and I tried $pullAll and it worked.
https://docs.mongodb.org/manual/reference/operator/update/pullAll/
I tried the simplified version of your data and $pull works:
> db.testcoll.insert({"containers": {"containreId": 1, "components": ["component1", "component2"]}})
> db.testcoll.insert({"containers": {"containreId": 2, "components": ["component3", "component1"]}})
> db.testcoll.find()
{ "_id" : ObjectId("53a8428ca2696f063b5c51eb"), "containers" : { "containreId" : 1, "components" : [ "component1", "component2" ] } }
{ "_id" : ObjectId("53a8429ea2696f063b5c51ec"), "containers" : { "containreId" : 2, "components" : [ "component3", "component1" ] } }
> db.testcoll.update({"containers.components": "component1"}, {$pull: {"containers.components": "component1"}}, {multi: true})
> db.testcoll.find()
{ "_id" : ObjectId("53a8428ca2696f063b5c51eb"), "containers" : { "components" : [ "component2" ], "containreId" : 1 } }
{ "_id" : ObjectId("53a8429ea2696f063b5c51ec"), "containers" : { "components" : [ "component3" ], "containreId" : 2 } }

Update array object based on id?

I'm having a bit of a mongo issue. I was wondering if there was a way to do the following in a mongo console command rather then multiple find and update calls.
{
"_id" : ObjectId("50b429ba0e27b508d854483e"),
"array" : [
{
"id" : "1",
"letter" : "a"
},
{
"id" : "2",
"letter" : "b"
}
],
"tester" : "tom"
}
I want to update the object with this new array item
{
"id": "2",
"letter": "c"
}
I used this, addToSet is limited, it won't insert an item into the array if it is already there but it will not update an item based on an identifier. In this case I would really like to update this entry based on the id.
db.soup.update({
"tester": "tom"
}, {
$addToSet: {
"array": {
"id": "2",
"letter": "c"
}
}
});
This gives me:
{
"_id" : ObjectId("50b429ba0e27b508d854483e"),
"array" : [
{
"id" : "1",
"letter" : "a"
},
{
"id" : "2",
"letter" : "b"
},
{
"id" : "2",
"letter" : "c"
}
],
"tester" : "tom"
}
When what I really wanted was:
{
"_id" : ObjectId("50b429ba0e27b508d854483e"),
"array" : [
{
"id" : "1",
"letter" : "a"
},
{
"id" : "2",
"letter" : "c"
}
],
"tester" : "tom"
}
You can use the $ positional operator to do this:
db.soup.update(
{_id: ObjectId("50b429ba0e27b508d854483e"), 'array.id': '2'},
{$set: {'array.$.letter': 'c'}})
The $ in the update object acts as a placeholder for the first element of array to match the query selector.
Here you go:
> db.collection.insert( { array : [ { id : 1, letter : 'a' }, { id : 2, letter : 'b' } ], tester : 'tom' } );
> db.collection.findOne();
{
"_id" : ObjectId("50b431a69a0358d590a2f5f0"),
"array" : [
{
"id" : 1,
"letter" : "a"
},
{
"id" : 2,
"letter" : "b"
}
],
"tester" : "tom"
}
> db.collection.update( { tester : 'tom' }, { $set : { 'array.1' : { id : 2, letter : 'c' } } }, false, true );
> db.collection.findOne();
{
"_id" : ObjectId("50b431a69a0358d590a2f5f0"),
"array" : [
{
"id" : 1,
"letter" : "a"
},
{
"id" : 2,
"letter" : "c"
}
],
"tester" : "tom"
}
The trick lies in the false, true, false.
That is: true for upsert, false for update multiple.
For more details check out:
http://www.mongodb.org/display/DOCS/Updating#Updating-update%28%29

Resources