Search Specific Element In array mongodb [duplicate] - mongodb

This question already has answers here:
How to filter array in subdocument with MongoDB [duplicate]
(3 answers)
Closed 6 years ago.
I am trying to find a specific object from array of objects in mongodb.
I am trying this
Company.findOne ({
"configuration.macAddress": "AB-90-dF-8d"
});
It returns me the exact company but it returns all the configuration array
I want only configuration with matching macAddress

Instead use aggregate(). $unwind the configuration array first, then you can $match the specific element only.
Company.aggregate([
{
"$unwind": "$configuration"
},
{
"$match":{
"configuration.macAddress": "AB-90-dF-8d"
}
}
]);

you can use $elemMatch to find a particular object in an array.
Company.find({ configuration: { $elemMatch: { macAddress: "AB-90-dF-8d"} } } );
can you show me your array of objects?

Related

Mongoose: How to return array of Object _ids within aggregation pipeline [duplicate]

This question already has answers here:
Return result as an Array of Values Only
(2 answers)
Closed 3 years ago.
I can format my response into this, an array of objects of _ids:
[ { "_id": "5d703c09af11414e538fe95b" }, { "_id": "5d704b9b1ba3f75232d778d4" }, { "_id": "5d704bbe1ba3f75232d779de" } ]
However is it possible, within the aggregation pipeline, to transform it into just an array of the Object ids:
["5d703c09af11414e538fe95b", "5d704b9b1ba3f75232d778d4", "5d704bbe1ba3f75232d779de"]
I am aware that I could simply take the original response and map over it but I am unsure if we could do this directly within mongooose.
use $group operator as
{$group:{_id:null,ids:{$push:"$_id"}}}
this will return an array of ids

updating multiple documents by passing a list objectids to findByIdAndUpdate [duplicate]

This question already has answers here:
MongoDB: How to update multiple documents with a single command?
(13 answers)
FindAndModify, return array of Objects
(1 answer)
Closed 5 years ago.
I am trying to use mongoose's findByIdAndUpdate method to pass in a list of object id's and updating them at once. However, I am getting a "Error: Can't use $set with ObjectId." error which I can't seem to associate with my code.
Here's my code.
return ComponentModel.findByIdAndUpdate({
_id: {
$in: input.subjectIds
},
$set: { location: input.newLocation }
}).then(res => res);
findByIdAndUpdate is for one document. For multiple documents you can use update with multi flag true.
return ComponentModel.update(
{_id: {$in: input.subjectIds}},
{$set: {location: input.newLocation}},
{"multi": true}
).then(res => res);

MongoDB : Add field in each array elements [duplicate]

This question already has answers here:
How to Update Multiple Array Elements in mongodb
(16 answers)
Closed 5 years ago.
I'm starting with mongoDB and I want to update a nested array in my documents to add some initial value, but I can't find a way to do it with mong.
here is my document :
{
"_id":"cTZDL7WThChSvsvBT",
"name":"abc",
"players":[
{
"playerName":"Name1"
},
{
"playerName":"Name2"
}
]
}
What I want to do :
{
"_id":"cTZDL7WThChSvsvBT",
"name":"abc",
"players":[
{
"playerName":"Name1",
"NewField1":0,
"NewField2":0
},
{
"playerName":"Name2",
"NewField1":0,
"NewField2":0
}
]
}
Does anyone have a solution for this kind of situation?
This adds the new fields to the player array ...
db.collection.update({_id: 'cTZDL7WThChSvsvBT', players: {$exists: true}}, {$set: {'players.$.NewFieldOne': 0, 'players.$.NewFieldTwo': 0}})
... but since Mongo will only update the first element of an array which matches the query you are a bit stuffed. You can, of course, choose which array element to update by using the positional operator (as in my example) or by choosing a specific element (as the previous poster suggested) but until Mongo supports 'array updates' on all elements I think you're left with a solution such as: find the relevant documents and then update each one (i.e. a client side update solution).
I finally found a way by editing directly the document in JS like this :
db.doc.find({_id: myDocId}).forEach(function (channel) {
channel.players.forEach(function (player) {
player.newField1 = 0;
player.newField2 = 0;
});
db.doc.update({_id: myDocId}, channel);
});
considering you want to update an element which is an object also,
how about this?
db.collections.updateOne({_id: "cTZDL7WThChSvsvBT"}, {$set: {"players.0.NewField1": 0, "players.0.NewField2: 0}});

MongoDb: add element to array if not exists [duplicate]

This question already has answers here:
Can you specify a key for $addToSet in Mongo?
(2 answers)
Closed 6 years ago.
I'm using node.js and Mongo.db (I'm newly on Mongo). I have a document like this:
Tag : {
name: string,
videoIDs: array
}
The idea is, the server receives a JSON like
JSON: {
name: "sport",
videoId: "34f54e34c"
}
with this JSON, it has to find the tag with the same name and check if in the array it has the videoId, if not, insert it to the array.
How can I check the array and append data?
You can use $addToSet operator to check exist before append element into array.
db.tags.update(
{name: 'sport'},
{$addToSet: { videoIDs: "34f54e34c" } }
);
In this update statement example, mongoDB will find the TAG document which matches name == sport, and then check whether the videoIDs array contains 34f54e34c. If not, append it to the array.
Detail usage of $addToSet please read here.
I didn't test it, but you can try something like:
yourDb.find({ name: "sport",
videoIDs: { $in: ["34f54e34c"] } })
.update({$addToSet: { videoIDs: "34f54e34c" }});
If you need how: MongoDb in nodeJs implementation, you can start with:
http://jsfiddle.net/1ku0z1a1/
$addToSet operator check for the empty or existing array in document.
db.col_name.update({name :"name_for_match"},{$addToSet : { videoId : "video_id_value"}})

Updating all elements in array [duplicate]

This question already has answers here:
How to Update Multiple Array Elements in mongodb
(16 answers)
Closed 8 years ago.
Hey I'm trying to update all subdocuments contained within an array using the following code
setDuelToInactive: (duel) ->
Duels.update({_id: duel._id}, $set: {active: false})
userOneId = duel.userOneId
userTwoId = duel.userTwoId
Users.update({_id: userOneId}, { $set: { 'profile.character.souls.$.active': false} })
Users.update({_id: userTwoId}, { $set: { 'profile.character.souls.$.active': false} })
return
where the souls field in the Users collection is the array. I receive the following error message
MongoError: Cannot apply the positional operator without a corresponding query field containing an array.
You cannot use the positional operator $ to update al subdocuments inside an array. See the documentation: the operator matches the first element of the array that matches the query.
This also means that your query should use the array field (profile.character.souls) somehow. Yours do not, hence the error.
At this moment there is no shortcut for what you intend to do, you need to list all indexes manually. See this question: How to Update Multiple Array Elements in mongodb