mongoDB: check if value exists in specific subdocument array [duplicate] - mongodb

This question already has answers here:
Retrieve only the queried element in an object array in MongoDB collection
(18 answers)
Closed 5 years ago.
I have the following schema:
{
_id: objectID('593f8c591aa95154cfebe612'),
name: 'test'
businesses: [
{
_id: objectID('5967bd5f1aa9515fd9cdc87f'),
likes: [objectID('595796811aa9514c862033a1'), objectID('593f8c591ba95154cfebe790')]
}
{
_id: objectID('59579ff91aa9514f600cbba6'),
likes: [objectID('693f8c554aa95154cfebe146')]
}
]
}
How can I check if objectID('593f8c591ba95154cfebe790') exists in the array business.likes where businesses._id = objectID('59579ff91aa9514f600cbba6') ?
In the above example it should return false.

You can use $elemMatch to find by multiple field in same sub document
db.collectionName.find({
businesses: {
$elemMatch: {
_id: ObjectId("5967bd5f1aa9515fd9cdc87f"),
likes: ObjectId("593f8c591ba95154cfebe790")
}
}
});

Related

How to update nested object property in MongoDB [duplicate]

This question already has answers here:
MongoDB - Update an object in nested Array
(4 answers)
Closed 1 year ago.
I have a data on MongoDB database which structure is
{
_id: 12478565,
products: { name: 'Mackbook Pro', price: 150000, color: 'silver' }
}
I want to update the products price and I write like this, but it gives an error
productsCollection.updateOne({_id: '12478565'}, {$set: {products.price: 190000} })
I want to know how can I modify the data in nested object?
put product.price in qoute
db.collection.update({
_id: "12478565"
},
{
$set: {
"products.price": 190000
}
})
https://mongoplayground.net/p/QxAK0LClF-8

Remove element of internal field array MongoDb [duplicate]

This question already has answers here:
MongoDB, remove object from array
(7 answers)
Closed 4 years ago.
I have the following situation:
{ code: 0, array:[{ _id: 1, ....}, { _id: 2, ....}, { _id: 18, ....}]}
I need to remove the element inside 'array' field matching the '_id' field.
How can I do that?
Thank you.
Use $update & $pull:
db.yourCollection.update(
{ }, // <-- your selection criteria
{ $pull: { array: { _id: 2 } } // <-- what you want to remove from which field
)

MongoDB update nested array of object by index [duplicate]

This question already has answers here:
Update field in exact element array in MongoDB
(5 answers)
Closed 5 years ago.
Let's suppose to there is db like below...
{ _id: 1234,
key: 'Contacts',
value: [
{ name: 'McDonald', phone: '1111'},
{ name: 'KFC', phone: '2222'}
]
}
And I want to change KFC's phone number to '3333'.
What I did is
DB.findOne({ key: 'Contacts' }, function(err, db){
db.value[1]['phone'] = '3333'
db.save(function(err, result){
// done
})
}
)
But it didn't update the database. What am I wrong?
There's no specific _id in elements of array for some reason.
Only the way to find specific element is index.
Use the positional operator $
more info : https://docs.mongodb.com/manual/reference/operator/update/positional/#up.S
DB.update({key: "Contacts", "value.name": "KFC" },
{ $set: { "value.$.phone" : 666 } },function(err,doc){
});

MongoDB find then query nested document [duplicate]

This question already has answers here:
Retrieve only the queried element in an object array in MongoDB collection
(18 answers)
Closed 5 years ago.
I'm trying to make a 'like' route that find user by _id then query inside user.post an object id, so far I tried this:
User.find({
"_id": logged_user,
"posts_id": {
$elemMatch: req.body.id
}
}, (err, data) => {
if (err) {
res.json(err)
}
console.log(data);
})
Schema:
username: String,
posts:[{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}]
it returns an empty array '[]', how can I return true of false if it exists?
You are using $elemMatch wrong. It needs an object. Do it this way:
User.find({"_id":logged_user,"posts":{$elemMatch: {$eq : req.body.id}}},(err,data)=>{
if(err){
res.json(err)
}
console.log(data);
)

Find the count of all the matching elements in an array [duplicate]

This question already has answers here:
Mongodb count all array elements in all objects matching by criteria
(2 answers)
Closed 4 years ago.
I need to find the count of all the matching array elements and count = 0 if the nested array do not contain values.
Here is my data entity structure.
{
name:A,
issues:[1,2,3,4]
}
{
name:B,
issues:[1,2]
}
{
name:C,
issues:[3,4]
}
If user search for issues:[1,2], I want my result set to look like
[{
name:A,
count:2
}
{
name:B,
count:2
}
{
name:C,
count:0
}]
I am using below query to achieve this but it only returns me result
[{
name:A,
count:2
}
{
name:B,
count:2
}]
which definitely I know because of the $match I am doing
{'$unwind':'$issues'}
,{'$match':{'allissues': {$in: p.issues? p.issues.map(Number):[]}}}
,{ '$group' :{_id:'$_id', name :{ $first: '$name' },count: { $sum: 1 }} }'
Given that issues variable is the array input by users, you do not need to use a three-stages aggregation like above to get the result. You just need to find the intersection of users input and issues field of each document, then get length of the result arrays. This code will do the job:
db.col.aggregate([{
$project: {
count: {
$size: {
$setIntersection: [issues, "$issues"]
}
}
}
}])