Update inner array in multiple array document - mongodb

I am trying this question... I don't want use the "_id" : "12", field..
{
"_id" : ObjectId("62622dd73905f04f59db2971"),
"array1" : [
{
"_id" : "12",
"array2" : [
{
"_id" : "123",
"answeredBy" : []
},
{
"_id" : "124",
"answeredBy" : []
}
]
}
]
}
I am trying to update using the following query
db.getCollection('nestedArray').updateMany(
{'array1.array2._id':'123'},
{$push:{'array1.array2.$[inner].answeredBy':'success'}},
{arrayFilters:[{'inner._id':'123'}]}
)
But I am getting the following error:
"errmsg" : "The path 'array1.array2' must exist in the document in
order to apply array updates.",
I just trying to understand what is wrong with the code....

add $[] between array1 and array2
Update Nested Arrays in Conjunction with $[]
db.collection.update({
"array1.array2._id": "123"
},
{
$push: {
"array1.$[].array2.$[inner].answeredBy": "success"
}
},
{
arrayFilters: [
{
"inner._id": "123"
}
]
})
mongoplayground

Related

How can I insert value in array inside object field in mongodb?

How can I insert an value in "total" array where pid = "123"
{
"_id" : ObjectId("625bc1983016ed5208bbdf90"),
"NAME" : "XYZ",
"data" : [
{
"pid" : "123",
"total" : [ ]
},
{
"pid" : "456",
"total" : [ ]
}
]
}
The right way is:
db.collection.update({
data: {
$elemMatch: {
pid: "123"
}
}
},
{
$set: {
"data.$.buyers": "some name"
}
})
$elemMatch allows you to match more than one component within the same array element and then you can use $set to update the specific element.
You can run it here to check the same query https://mongoplayground.net/p/lveZw-8wkZ0
You can also have a look at documentation of $elemMatch in this link.
Let me know if you face any issue.

MongoDB: projection $ when find document into nested arrays

I have the following document of collection "user" than contains two nested arrays:
{
"person" : {
"personId" : 78,
"firstName" : "Mario",
"surname1" : "LOPEZ",
"surname2" : "SEGOVIA"
},
"accounts" : [
{
"accountId" : 42,
"accountRegisterDate" : "2018-01-04",
"banks" : [
{
"bankId" : 1,
"name" : "Bank LTD",
},
{
"bankId" : 2,
"name" : "Bank 2 Corp",
}
]
},
{
"accountId" : 43,
"accountRegisterDate" : "2018-01-04",
"banks" : [
{
"bankId" : 3,
"name" : "Another Bank",
},
{
"bankId" : 4,
"name" : "BCT bank",
}
]
}
]
}
I'm trying to get a query that will find this document and get only this subdocument at output:
{
"bankId" : 3,
"name" : "Another Bank",
}
I'm getting really stucked. If I run this query:
{ "accounts.banks.bankId": "3" }
Gets the whole document. And I've trying combinations of projection with no success:
{"accounts.banks.0.$": 1} //returns two elements of array "banks"
{"accounts.banks.0": 1} //empty bank array
Maybe that's not the way to query for this and I'm going in bad direction.
Can you please help me?
You can try following solution:
db.user.aggregate([
{ $unwind: "$accounts" },
{ $match: { "accounts.banks.bankId": 3 } },
{
$project: {
items: {
$filter: {
input: "$accounts.banks",
as: "bank",
cond: { $eq: [ "$$bank.bankId", 3 ] }
}
}
}
},
{
$replaceRoot : {
newRoot: { $arrayElemAt: [ "$items", 0 ] }
}
}
])
To be able to filter accounts by bankId you need to $unwind them. Then you can match accounts to the one having bankId equal to 3. Since banks is another nested array, you can filter it using $filter operator. This will give you one element nested in items array. To get rid of the nesting you can use $replaceRoot with $arrayElemAt.

How to check if nested arrays are ALL empty in mongodb?

I have something like below:
{
"_id" : "1",
"firstArray" : [
{
"_id" : "11",
"secondArray" : [ ]
},
{
"_id" : "12",
"secondArray" : [ ]
},
{
"_id" : "13",
"secondArray" : [ { "type" : "somthing" } ]
}
]
},
{
"_id" : "2",
"firstArray" : [
{
"_id" : "21",
"secondArray" : [ ]
},
{
"_id" : "22",
"secondArray" : [ ]
}
]
}
I need a mongodb query to find documents which ALL of the nested secondArrays are empty? the query should return second document and not the first one.
to solve that, we need to check size of arr2, but to enable that we need first to unwind arr1.
Please find below aggregation framework snippet which solves this problem,
db.pmoubed.aggregate([{
$unwind : "$firstArray"
}, {
$project : {
_id : 1,
firstArray : 1,
isNotEmpty : {
$size : "$firstArray.secondArray"
}
}
}, {
$group : {
_id : "$_id",
isNotEmpty : {
$sum : "$isNotEmpty"
},
firstArray : {
$push : "$firstArray"
}
}
}, {
$match : {
"isNotEmpty" : 0
}
}
])
Any comments welcome

Retrieve the second element of array for each document - MongoDB

I have a MongoDB collection, called bios, that contains documents similar to these:
{
"_id" : ObjectId("51df07b094c6acd67e492f41"),
"name" : {
"first" : "John",
"last" : "McCarthy"
},
"birth" : ISODate("1927-09-04T04:00:00Z"),
"death" : ISODate("2011-12-24T05:00:00Z"),
"contribs" : [
"Lisp",
"Artificial Intelligence",
"ALGOL"
]
},
{
"_id" : 3,
"name" : {
"first" : "Grace",
"last" : "Hopper"
},
"title" : "Rear Admiral",
"birth" : ISODate("1906-12-09T05:00:00Z"),
"death" : ISODate("1992-01-01T05:00:00Z"),
"contribs" : [
"UNIVAC",
"compiler",
"FLOW-MATIC",
"COBOL"
]
}
My target is to retrieve the second element of the array contribs for each document in bios collection.
Using the new aggregation pipeline operator $filter I run the following query:
> db.bios.aggregate([
{
$match: {"contribs.2":{"$exists":1}}},
{
$project:{contribs:
{
$filter:{input:"$contribs", as: "contribs", cond:{}}},_id:0}}])
With my query, the output is:
{ "contribs" : [ "Lisp", "Artificial Intelligence", "ALGOL" ] }
{ "contribs" : [ "UNIVAC", "compiler", "FLOW-MATIC", "COBOL" ] }
that is not just the second element of the array contribs but a projection on contribs array when its second element exists.
did you try $elementAt ?
db.bios.aggregate([
{ $match: {"contribs.1": { "$exists": 1 } }},
{ $project: { contribs: { $arrayElemAt: [ "$contribs", 1 ] } } }
]);

Update Query in MongoDB with where conditions

{
"_id" : ObjectId("510902fb7995fe3504000002"),
"name" : "Gym",
"status" : "1",
"whichs" : [
{
"name" : "American",
"status" : "1"
}
]
}
Above is my collection object.. I want to update which.name to "Indian" where which.status = 1.. Please help me with the mongoDB query for doing this..
You can try this:
db.collection.update({"whichs.status" : "1" },
{$set : { "whichs.$.name" : "Indian"},
false,
true);
This finds "whichs.status" : "1" then sets "whichs.$.name" : "Indian" for all documents. For more info on the update() method, read here.
Starting from MongoDB v3.6, you can use arrayFilters, to perform array update operation.
db.collection.update({
"whichs.status": "1"
},
{
$set: {
"whichs.$[element].name": "Indian"
}
},
{
arrayFilters: [
{
"element.status": "1"
}
]
})
Mongo Playground