Is possible to query mongodb on array keys? - mongodb

My table has an array indexed by a string, and i want all the records matching this string, no matter what the value is. For example get all the record wher id1 is fill :
var a = {
type: "Information",
ids: {
'id1' : '123'
'id2' : '456'
}
};
var b = {
type: "Information",
ids: {
'id1' : '789'
}
};
Is it possible to do that with mongodb and how?

You can use $exists for this:
> db.things.insert({'type': 'Information', 'ids':{'id1': 123, 'id2': 456}})
> db.things.insert({'type': 'Information', 'ids':{'id1': 746, 'id2': 456}})
> db.things.insert({'type': 'Information', 'ids':{'id2': 456, 'id3': 936}})
> db.things.find({'ids.id1': {'$exists': true}})
{ "_id" : ObjectId("4dd3c706938307861ed610dd"), "type" : "Information", "ids" : { "id1" : 123, "id2" : 456 } }
{ "_id" : ObjectId("4dd3c7a1938307861ed610de"), "type" : "Information", "ids" : { "id1" : 746, "id2" : 456 } }

Thanks to scoates in #mondodb channel, it's possible to do that with exists function : http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24exists
db.Information.find({"ids.id1":{$exists:true}});

Related

I am new to mongoDB need a query to delete the collections

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.

mongodb join-like query with two collections and a where clause

Suppose we have following collections in a database:
db.documents.insert([{'name': 'A'}, {'name': 'B'}, {'name': 'C'}])
db.fragments.insert([{'value:': 'A1', doc_name: 'A'}, {'value:': 'A2', doc_name: 'A'},
{'value:': 'B1', doc_name: 'B'}, {'value:': 'B2', doc_name: 'B'},
{'value:': 'C1', doc_name: 'C'}, {'value:': 'C2', doc_name: 'C'}])
where documents collection stores the names of the documents (and other stuff omitted in this example), fragments collections refers by doc_name to a document related to the fragment.
Now, if I only want to consider a subset of documents
> db.documents.find().limit(2)
{ "_id" : ObjectId("52d1a3bf49da25160ad6f076"), "name" : "A" }
{ "_id" : ObjectId("52d1a3bf49da25160ad6f077"), "name" : "B" }
then how can I see the fragments of associated to these selected documents, so I would get
{ "_id" : ObjectId("52d1a3bf49da25160ad6f079"), "value:" : "A1", "doc_name" : "A" }
{ "_id" : ObjectId("52d1a3bf49da25160ad6f07a"), "value:" : "A2", "doc_name" : "A" }
{ "_id" : ObjectId("52d1a3bf49da25160ad6f07b"), "value:" : "B1", "doc_name" : "B" }
{ "_id" : ObjectId("52d1a3bf49da25160ad6f07c"), "value:" : "B2", "doc_name" : "B" }
As a solution, I was thinking that I should store the document names in an array, something like var docnames = ??? such that
> docnames
[ "A", "B" ]
and then trying to use this array in a where clause, something like
> db.fragments.find({$where: function(x) { return (this.doc_name in docnames)}})
error: {
"$err" : "ReferenceError: docnames is not defined near 'c_name in docnames)}' ",
"code" : 16722
}
But as I am very new to mongodb, so I am having trouble figuring it out. I believe this could be done as a one-liner as well.
db.fragments.find( { 'doc_name': { $in : ['A' , 'B'] } } );
Execute this commands in mongo:
var f = db.documents.find().limit(2) , n = [];
for (var i = 0; i < f.length(); i++) n.push(f[i]['name']);
db.fragments.find( { 'doc_name': { $in : n } } );

Updating an array of objects with a new key in mongoDB

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.

Update an element in sub of sub array in mongodb

I have this data in Mongo:
{
"_id" : ObjectId("505fd43fdbed3dd93f0ae088"),
"categoryName" : "Cat 1",
"services" : [
{
"serviceName" : "Svc 1",
"input" : [
{ "quantity" : 10, "note" : "quantity = 10" },
{ "quantity" : 20, "note" : "quantity = 20" }
]
},
{
"serviceName" : "Svc 2",
"input" : [
{ "quantity" : 30, "note" : "quantity = 30" },
{ "quantity" : 40, "note" : "quantity = 40" }
]
}
]
}
Now I want to update a quantity for "Svc 1":
{ "quantity" : 10, "note" : "quantity = 10" }
Like:
{"quantity": 100, "note": "changed to 100"}
How can I do with Mongo?`
As I know, operational operator only supports for the first array, someone advised to use index of an element of the sub sub array, but the problem is that how can know that index at run time? (I'm using native C# driver of MongoDB)
Thanks in advance for your helps!
Johnny
Since you have an array within an array, there isn't any easy way to reference the nested subarray unless you know the position in the array you want to update.
So, for example, you could update the first input for 'Svc 1' with the C# equivalent of:
db.services.update(
// Criteria
{
'_id' : ObjectId("505fd43fdbed3dd93f0ae088"),
'services.serviceName' : 'Svc 1'
},
// Updates
{
$set : {
'services.$.input.0.quantity' : 100,
'services.$.input.0.note' : 'Quantity updated to 100'
}
}
)
If you don't know the position for the nested input array, you will have to fetch the matching services, iterate the input array in your application code, then $set the updated array.
Alternatively, you could modify your nested array to use an embedded document instead, eg:
{
"categoryName" : "Cat 1",
"services" : [
{
"serviceName" : "Svc 1",
"input1" : { "quantity" : 10, "note" : "quantity = 10" },
"input2" : { "quantity" : 20, "note" : "quantity = 20" }
},
]
}
Which you could then update by name, eg input1:
db.services.update(
// Criteria
{
'_id' : ObjectId("5063e80a275c457549de2362"),
'services.serviceName' : 'Svc 1'
},
// Updates
{
$set : {
'services.$.input1.quantity' : 100,
'services.$.input1.note' : 'Quantity updated to 100'
}
}
)
Since you don't know the position of the value wanted to update, first insert a new value with updated information and then remove the value wanted to update.
db.services.update(
{
'_id' : ObjectId("505fd43fdbed3dd93f0ae088"),
'services.serviceName' : 'Svc 1'
},
{
{ $addToSet: { 'services.$.input' : "new sub-Doc" }
}
)
And then remove when insert is success
db.services.update(
{
'_id' : ObjectId("505fd43fdbed3dd93f0ae088"),
'services.serviceName' : 'Svc 1'
},
{
{ $pull: { 'services.$.input' : { "quantity" : 10, "note" : "quantity = 10" } }
}
)
This is useful when index is not known and document should have sub-documents having same key like "input" in post Update an element in sub of sub array in mongodb

MongoDB find where key equals string from array

I am trying to find in a collection all of the documents that have the given key equal to one of the strings in an array.
Heres an example of the collection.
{
roomId = 'room1',
name = 'first'
},
{
roomId = 'room2',
name = 'second'
},
{
roomId = 'room3',
name = 'third'
}
And heres an example of the array to look through.
[ 'room2', 'room3' ]
What i thought would work is...
collection.find({ roomId : { $in : [ 'room2', 'room3' ]}}, function( e, r )
{
// r should return the second and third room
});
How can i achieve this?
One way this could be solve would be to do a for loop...
var roomIds = [ 'room2', 'room3' ];
for ( var i=0; i < roomIds.length; i++ )
{
collection.find({ id : roomIds[ i ]})
}
But this is not ideal....
What you posted should work - no looping required. The $in operator does the job:
> db.Room.insert({ "_id" : 1, name: 'first'});
> db.Room.insert({ "_id" : 2, name: 'second'});
> db.Room.insert({ "_id" : 3, name: 'third'});
> // test w/ int
> db.Room.find({ "_id" : { $in : [1, 2] }});
{ "_id" : 1, "name" : "first" }
{ "_id" : 2, "name" : "second" }
> // test w/ strings
> db.Room.find({ "name" : { $in : ['first', 'third'] }});
{ "_id" : 1, "name" : "first" }
{ "_id" : 3, "name" : "third" }
Isn't that what you expect?
Tested w/ MongoDB 2.1.1