I am a beginner in mongo db, I have this sample in my database
{
"_id" : ObjectId("5a95cef390bd8fbf1c699d73"),
"dr_asin" : "0439394422",
"dr_description" : "Product that encourages families to learn, explore, and create in new and exciting ways.",
"dr_price" : 12.96,
"dr_imUrl" : "http://ecx.images-amazon.com/images/I/51Zx2bIwWcL._SX300_.jpg",
"dr_related" : {
"also_bought" : [
"B0002667BI",
"B00005JKTY",
"B0002667B8"
],
"buy_after_viewing" : [
"B00005JKTY",
"B00000DGSW",
"B0002667BI"
]
},
"dr_salesRank" : {
"Video Games" : 36531
},
"dr_categories" : [
[
"Video Games",
"Mac",
"Games"
],
[
"Video Games",
"PC",
"Games"
]
]
}
I want to find all products that are in the Mac category, I tried all these
db.P15242570_products.find({dr_categories: {$in: ["Mac"]}})
db.P15242570_products.find( { 'dr_categories.Mac': { $exists: true } } )
db.P15242570_products.find({ dr_categories: "Mac" }
db.P15242570_products.find({ dr_categories : { $all : ['Mac'] }});
but nothing is working ? any ideas ?
This worked for me
db.15242570_products.find({"dr_categories":{$elemMatch:{$elemMatch:{$in:["PC"]}}});
Related
I have two collections.
1.Equipment
db.getCollection("Equipment").find({
$and: [
{ $where: 'this._id.length <= 7' },
{ "model": "A505"}
]})
{
"_id" : "1234567",
"locationId" : "DATALOAD",
"model" : "A505",
"subscriberId" : "",
"status" : "Stock",
"headendNumber" : "4"
}
{
"_id" : "P13050I",
"locationId" : "1423110302801",
"model" : "A505",
"subscriberId" : "37",
"status" : "Stock",
"headendNumber" : "4"
}
I will get more than 100 documents (rows) Equipment collection.
2.Subscriber
db.getCollection('Subscriber').find({})
{
"_id" : "5622351",
"equipment" : [
"0018015094E6",
"1234567",
"ADFB70878422",
"M10610TCB052",
"MA1113FHQ151"
]
}
{
"_id" : "490001508063",
"equipment" : [
"17616644510288",
"P13050I",
"M91416EA4251",
"128552270280560"
]
}
In the Subscriber collection, I need to remove (get all the id from Equipment collection loop it) only the matches equipment field.
Forex from the above result, I need to remove only "1234567", and "P13050I"
Expected output.
db.getCollection('Subscriber').find({})
{
"_id" : "5622351",
"equipment" : [
"0018015094E6",
"ADFB70878422",
"M10610TCB052",
"MA1113FHQ151"
]
}
{
"_id" : "490001508063",
"equipment" : [
"17616644510288",
"M91416EA4251",
"128552270280560"
]
}
Please help me, anyone.
You can use the following to update records.
Let's find records which need to deleted and store them in array
var equipments = [];
db.getCollection("Equipment").find({ $and: [
{ $where: 'this._id.length <= 7' },
{ "model": "A505"}
]}).forEach(function(item) => {
equipments.push(item._id)
})
Now, iterate over records of the second collection and update if required.
db.getCollection('Subscriber').find({}).forEach(function(document) => {
var filtered = document.equiment.filter(id => equipments.indexOf(id) < 0);
if(filtered.length < document.equipment.length){
db.getCollection('Subscriber').update({"_id": document.id }, { $set: {'equipment': filtered}})
}
})
.filter(id => equipments.indexOf(id) < 0) will keep entries which is not present in initially populated array equipments and it will persist if there is any change.
I am the beginner of the MongoDB
Here I mentioned my database schema
{
"_id" : ObjectId("5e72067973c1241068a13647"),
"client_id" : "1001",
"dependent" : [
{
"dependent_name" : "asdsa",
"dependent_id" : "DE100"
},
{
"dependent_name" : "fdggd",
"dependent_id" : "DE101"
}
]
}
I want to add new field based on client_id and dependent_id
Here I mentioned My query but cannot able to get my expected result
db.collection.update({"client_id" : "1001","dependent.dependent_id":"DE101"}, {"$push": {"reason":"expired"}})
I am Expected Result is
{
"_id" : ObjectId("5e72067973c1241068a13647"),
"client_id" : "1001",
"dependent" : [
{
"dependent_name" : "asdsa",
"dependent_id" : "DE100"
},
{
"dependent_name" : "fdggd",
"dependent_id" : "DE101",
"reason":"expired"
}
]
}
so anyone help me to solve this
db.collection.update({"client_id" : "1001","dependent.dependent_id":"DE101"},
{$set:
{"dependent.$.reason":"expired"}})
Try this it works for me using $
As i am also new to mongodb, as i tried, i can give you suggestion to update whole document or replace it.
both way i tried, and query is as below.
Update
db.updateColl.update({ 'dependent.dependent_id': 'DE101' },
{
$set: {
"dependent": [
{
"dependent_name": "asdsa",
"dependent_id": "DE100"
},
{
"dependent_name": "fdggd",
"dependent_id": "DE101",
"reason": "expired"
}
]
}
});
Replace
db.updateColl.replaceOne({ 'dependent.dependent_id': 'DE101' }, {
"dependent": [
{
"dependent_name": "asdsa",
"dependent_id": "DE100"
},
{
"dependent_name": "fdggd",
"dependent_id": "DE101",
"reason": "expired"
}
]
})
may be it can help you. if any suggestion regarding it wellcome.
I have a Meteor Mongo document as shown below
{
"_id" : "zFndWBZTvZPgSKXHP",
"activityId" : "aRDABihAYFoAW7jbC",
"activityTitle" : "Test Mongo Document",
"users" : [
{
"id" : "b1#gmail.com",
"type" : "free"
},
{
"id" : "JqKvymryNaCjjKrAR",
"type" : "free"
},
],
}
I want to update a specific array element's email with custom generated id using Meteor query something like the below.
for instance, I want to update the document
if 'users.id' == "b1#gmail.com" then update it to users.id = 'SomeIDXXX'
So updated document should looks like below.
{
"_id" : "zFndWBZTvZPgSKXHP",
"activityId" : "aRDABihAYFoAW7jbC",
"activityTitle" : "Test Mongo Document",
"users" : [
{
"id" : "SomeIDXXX",
"type" : "free"
},
{
"id" : "JqKvymryNaCjjKrAR",
"type" : "free"
},
],
}
I have tried the below but didnt work.
Divisions.update(
{ activityId: activityId, "users.id": emailId },
{ $set: { "users": { id: _id } } }
);
Can someone help me with the relevant Meteor query ? Thanks !
Your query is actually almost right except for a small part where we want to identify the element to be updated by its index.
Divisions.update({
"activityId": "aRDABihAYFoAW7jbC",
"users.id": "b1#gmail.com"
}, {
$set: {"users.$.id": "b2#gmail.com"}
})
You might need the arrayFilters option.
Divisions.update(
{ activityId: activityId },
{ $set: { "users.$[elem].id": "SomeIDXXX" } },
{ arrayFilters: [ { "elem.id": "b1#gmail.com" } ], multi: true }
);
https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/
You need to use the $push operator instead of $set.
{ $push: { <field1>: <value1>, ... } }
The following questions refer to my example.
How do I create an index for the ids in idsAndNames map?
I want to search these numbers: 7065362, 7064458, 7065003, 7064286...
How do I create an index for the strings in subTargets list?
I want to search these strings: ALL, ACTION, DRAMA...
My example:
{
"_id" : ObjectId("sdfsdfsdfsdfsdfsd910d41ad9"),
"targets" : {
"Superheroes" : {
"idsAndNames" : {
"7065362" : "Doctor Strange",
"7064458" : "Dr. Manhattan",
"7065003" : "Captain Atom",
"7064286" : "Hulk"
},
"subTargets" : [
"ALL",
"ACTION",
"DRAMA"
]
}
"BestSuperheroes" : {
"idsAndNames" : {
"7065362" : "Superman",
"7064458" : "Thor",
"7065003" : "Professor X",
"7064286" : "Batman"
},
"subTargets" : [
"ALL",
"SCIFI",
"CHICKFLICKS"
]
}
}
...
}
Before trying to create an index maybe you should review your schema, changing it to something like:
...
"Superheores" : [
{
"id": "7065362",
"name": "Doctor Strange"
}]
So you can use db.collection.ensureIndex({'targets.Superheroes.id': 1});. You won't be able to create an effective index if you have dynamic key names.
And for the text, you could try the text search index.
Similar to this question
Barrowing the data set, I have something similar to this:
{
'user_id':'{1231mjnD-32JIjn-3213}',
'name':'John',
'campaigns':
[
{
'campaign_id':3221,
'start_date':'12-01-2012',
},
{
'campaign_id':3222,
'start_date':'13-01-2012',
}
]
}
And I want to add a new key in the campaigns like so:
{
'user_id':'{1231mjnD-32JIjn-3213}',
'name':'John',
'campaigns':
[
{
'campaign_id':3221,
'start_date':'12-01-2012',
'worker_id': '00000'
},
{
'campaign_id':3222,
'start_date':'13-01-2012',
'worker_id': '00000'
}
]
}
How to insert/update a new key into an array of objects?
I want to add a new key into every object inside the array with a default value of 00000.
I have tried:
db.test.update({}, {$set: {'campaigns.worker_id': 00000}}, true, true)
db.test.update({}, {$set: {campaigns: {worker_id': 00000}}}, true, true)
Any suggestions?
I'm supposing that this operation will occur once, so you can use a script to handle it:
var docs = db.test.find();
for(var i in docs) {
var document = docs[i];
for(var j in document.campaigns) {
var campaign = document.campaigns[j];
campaign.worker_id = '00000';
}
db.test.save(document);
}
The script will iterate over all documents in your collection then over all campaigns in each document, setting the *worker_id* property.
At the end, each document is persisted.
db.test.update({}, {$set: {'campaigns.0.worker_id': 00000}}, true, true
this will update 0 element.
if you want to add a new key into every object inside the array you should use:
$unwind
example:
{
title : "this is my title" ,
author : "bob" ,
posted : new Date() ,
pageViews : 5 ,
tags : [ "fun" , "good" , "fun" ] ,
comments : [
{ author :"joe" , text : "this is cool" } ,
{ author :"sam" , text : "this is bad" }
],
other : { foo : 5 }
}
unwinding tags
db.article.aggregate(
{ $project : {
author : 1 ,
title : 1 ,
tags : 1
}},
{ $unwind : "$tags" }
);
result:
{
"result" : [
{
"_id" : ObjectId("4e6e4ef557b77501a49233f6"),
"title" : "this is my title",
"author" : "bob",
"tags" : "fun"
},
{
"_id" : ObjectId("4e6e4ef557b77501a49233f6"),
"title" : "this is my title",
"author" : "bob",
"tags" : "good"
},
{
"_id" : ObjectId("4e6e4ef557b77501a49233f6"),
"title" : "this is my title",
"author" : "bob",
"tags" : "fun"
}
],
"OK" : 1
}
After you could write simple updaiting query.