I need to get the value "no_tilt" but I just cannot figure it out, I was trying something like this..
collectionName.find({
"Shape.layers.vector_tagging": {
$elemMatch: { "1.shapes": { $elemMatch: {0: "Label"} } }}
})
Ok so I downloaded Robot 3T and started testing, and I was finally able to do it, here it is in case anyone finds it useful
db.getCollection('myCollection').find({
"Shape.layers.vector_tagging": {
$elemMatch: { "shapes": { $elemMatch: {"tags.Label":"no_tilt"} } }}
})
Related
Just looking for a bit of guidance. I am connected to my local mongoDB instance and I am trying to build a query that will add a unique objectID to every object in an array that doesn't have an _id already. I am trying to do this in nestjs so I can utilize javascript and get a unique ObjectID. Here is what I have so far.
const temp = await this.vehiclesRepository.updateMany(
{
$stipulations: [],
},
{
$set: {
$stipulations: {
$function: {
body: "function (ar) {return ar.map(x => { if(x.hasOwnProperty('_id')) return x; else {x['_id']=new ObjectId(); return x;}})}",
args: ['$stipulations'],
lang: 'js',
},
},
},
},
);
public async updateMany(filter: FilterQuery<T>, doc: UpdateQuery<T>) {
this.model.updateMany(filter, doc, { upsert: true, multi: true });
}
Can anyone tell me where I am going wrong with this? Based on my research this seems like the proper method to accomplish this task.
The $function operator is an aggregation operator. You should use it within an aggregation pipeline. There is also a $set operator specifically meant for aggregations.
You should combine the $function and $set (aggregation) operators within an aggregation pipeline.
I was able to answer my question in the MongoDB shell, with no javascript like so
db.vehicles.find().forEach(function(doc){
if(doc.stipulations != null) {
if(doc.stipulations.length > 0) {
doc.stipulations.forEach(function(stip) {
if(stip._id == null) {
stip._id = new ObjectId();
}
});
}
}
db.vehicles.updateOne({_id: doc._id}, {$set: doc});
});
For optimization it is possible to filter purely in find(), but for this one time query I am not posting that.
I want to paginate an array of documents called "Reviews" but I can't find a way to do it, since the code I execute paginate the documents for me and not the array of documents "Reviews".
Code you tried to run
return await this.animeModel
.aggregate()
.match({ _id: Types.ObjectId(reviewPaginateData.animeId) })
.unwind('$reviews')
.group({
_id: '$_id',
reviews: { $push: '$reviews' },
})
.sort(reviewPaginateData.sort)
.limit(reviewPaginateData.limit)
.skip(reviewPaginateData.limit * reviewPaginateData.skip)
.exec();
Document structure
Any way to solve this problem? Thank you very much in advance.
I don't have much experience with mongoose, but I can write a shell query to perform the pagination on an array. So, that you can integrate it in mongoose.
The reason you are not able to paginate is that you are applying the skip and limit after group which is giving you an array as output. So, to apply pagination on the array itself you need to use $slice for more read here
db.collection.aggregate([
{
$match:{
"_id":ObjectId("xyz")
}
},
{
$unwind:"$reviews"
},
{
$group:{
"_id":"$_id",
"reviews":{
$push:"$reviews"
}
}
},
{
$sort:{
sort_value:1
}
},
{
$project:{
"reviews":{
$slice:[
"$reviews",
skip_value,
limit_value
]
}
}
}
]).pretty()
Hope this will help :)
I'm currently learning full-stack development and I'm having trouble on a task where I have to insert a movie ID into a users list of favourites using Mongodb.
The user I've created is:
{ "_id" : ObjectId("5e1501c6abeeaf482847d46e"),
"UserName": "JulijaDa",
"Password": "FwPreviledges",
"Email": "Julija.Da#live.ru",
"Birhday": {
"$date": "1995-03-16T00:00:00.000Z"
},
"Favs":[
{
"ObjectId": "5e1352793e9e6a804448db0c"
}
]
}
This user currently has only one favourite movie (5e1352793e9e6a804448db0c) and I need to add another (5e1352793e9e6a804448db0e) but, using this method:
db.user.update({
"UserName": "JulijaDa"
}, {
$push: {
"Favs": ObjectId("5e1352793e9e6a804448db0e")
}
})
Mongo returns:
WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })
I'm following the instructions but, honestly, I'm starting to pull my hair out over here. Can someone tell me what I'm doing wrong? I can also provide more information if needed but, this is basically all I have right now!
Thank you in advance
Through a lot of trial and error, it seems the required code to add a favourite to his user in the database is:
db.[collection name].update(
{ _id: ObjectId("[ID of item being updated]") },
{ $push: { [Name of key]: { [value being added] } } }
)
In the above example, it would look like this:
db.users.update(
{ _id: ObjectId("5e1501c6abeeaf482847d46e") },
{ $push: { Favs: { ObjectId: "5e1352793e9e6a804448db0e" } } }
)
This will added the correct value to the correct fields.
I hope this helps other who are struggling too.
Hi guys so I'm doing meteor mongo db, I use findAndModify package
Ips.findAndModify({
//Find the desired document based on specified criteria
query: {
"ipAdr": clientIp,
connections: {
$elemMatch: {
connID: clientConnId
}
}
},
//Update only the elements of the array where the specified criteria matches
update: {
$push: {
'connections': {
vid: result.data.vid,
firstName: result.data.properties.firstname.value,
lastName: result.data.properties.lastname.value
}
}
}); //Ips.findAndModify
So I find the element that I need however my info is being pushed to the whole connections array, but I want to push my info into that specific element. What should I do here? I tried
$push: {
'connections.$': {
vid: result.data.vid,
but it gives error.
Please help.
You don't need to use the $push operator here as it adds a new element to array, instead you need to modify an element that is already in the array, try the $set operator to update as follows:
update: {
$set: {
'connections.$.vid': result.data.vid,
'connections.$.firstName': result.data.properties.firstname.value,
'connections.$.lastName': result.data.properties.lastname.value
}
}
Take into account that this way you will change only one element of the array that satisfies the condition from the $elemMatch statement.
I have a document in mongodb with 2 level deep nested array of objects that I need to update, something like this.
{
"id":12362,
"onGoing":[
{
"id":14597,
"offers":[
{
"id":56897,
"status":"validated"
},
{
"id":86127,
"status":"validated"
}
]
},
{
"id":89451,
"offers":[
{
"id":12235,
"status":"validated"
},
{
"id":56457,
"status":"validated"
}
]
}
]
}
I would like to update all offers matching with their id.
I have tried to update like
db.repairJobs.update({
"onGoing.offers":{
$elemMatch:{
_id:{
$in:[
'56897', '56457'
]
}
}
}
},
{
$set:{
"ongoing.offers.$.status":"ACCEPTED"
}
});
But getting the error: cannot use the part (ongoing of ongoing.offers.0.status) to traverse the element ({ongoing: [ { _id: null, ...
Are there any ways to update, the solution need to be compatible with spring Data.
As far as I know there is no way to update documents two level deep in MongoDB. I stumbled upon this JIRA item. I don't think there's a way to use multiple $ operators in update operations.
https://jira.mongodb.org/browse/SERVER-831
I am not aware of any workarounds based on your current schema but I would recommend you to let's say, split your each of your onGoing arrays into different documents.
You can use array filters to do this
Update Nested Arrays in Conjunction with $[]
as for your question, my solution is
db.repairJobs.update(
{},
{
$set: {
"onGoing.$[].offers.$[elem].status": "ACCEPTED"
}
},
{
arrayFilters: [{ "elem.id": {$in: [56897, 56457]} }],
multi: true
});