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

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 } } );

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, how to use document as the smallest unit to search the document in array?

Sorry for the title, but I really do not know how to make it clear. But I can show you.
Here I have insert two document
> db.test.find().pretty()
{
"_id" : ObjectId("557faa461ec825d473b21422"),
"c" : [
{
"a" : 3,
"b" : 7
}
]
}
{
"_id" : ObjectId("557faa4c1ec825d473b21423"),
"c" : [
{
"a" : 1,
"b" : 3
},
{
"a" : 5,
"b" : 9
}
]
}
>
I only want to select the first document with a value which is greater than 'a' and smaller than 'b', like '4'.
But when i search, i cannot get the result i want
> db.test.find({'c.a': {$lte: 4}, 'c.b': {$gte: 4}})
{ "_id" : ObjectId("557faa461ec825d473b21422"), "c" : [ { "a" : 3, "b" : 7 } ] }
{ "_id" : ObjectId("557faa4c1ec825d473b21423"), "c" : [ { "a" : 1, "b" : 3 }, { "a" : 5, "b" : 9 } ] }
>
Because '4' is greater than the '"a" : 1' and smaller than '"b" : 9' in the second document even it is not in the same document in the array, so the second one selected.
But I only want the first one selected.
I found this http://docs.mongodb.org/manual/reference/operator/query/elemMatch/#op._S_elemMatch, but it seems the example is not suitable for my situation.
You would want to
db.test.findOne({ c: {$elemMatch: {a: {$lte: 4}, b: {$gte: 4} } } })
With your query, you are searching for documents that have an object in the 'c' array that has a key 'a' with a value <= 4, and a key 'b' with a value >= 4.
The second record is return because c[0].a is <= 4, and c[1].b is >= 4.
Since you specified you wanted to select only the first document, you would want to do a findOne() instead of a find().
Use $elemMatch as below :
db.test.find({"c":{"$elemMatch":{"a":{"$lte":4},"b":{"$gte":4}}}})
Or
db.test.find({"c":{"$elemMatch":{"a":{"$lte":4},"b":{"$gte":4}}}},{"c.$":1})

Get all objects for each tag

I'm new in mongodbs mapreduce and for sure I have not completely understood it for now. And I have a problem, which I try to solve for few days without success.
I have a collection of let's say posts with a tags field. Now I want to mapreduce a new collection of tags. Where every tag have an array of all posts ids that have this one particular tag assigned.
one of my attempts to do this (which doesn't do this right)
m = function() {
for (var i in this.tags) {
emit(this.tags[i], {"ids" : [this._id]});
};
}
r = function(key, emits) {
var total = {ids : []}
for (var i in emits) {
emits[i].ids.forEach(function(id) {
total.ids.push(id);
}
}
return total;
};
I know, that I have to pivot the date some how around, but I just cant get my head wrapped around it.
I think you're missing a ")" in your reduce function to close the emits[i].ids.forEach(). Is this what you're trying to do?
r = function (key, values) {
var total = {ids:[]};
for (var i in values) {
values[i].ids.forEach(
function (id){
total.ids.push(id);
}
);
}
return total;
}
input
{_id:2, tags: ["dog", "Jenna"]}
{_id:1, tags: ["cat", "Jenna"]}
result:
{"results" : [
{"_id" : "Jenna",
"value" : {"ids" : [2,1]}
},
{"_id" : "cat",
"value" : {"ids" : [1]}
},
{"_id" : "dog",
"value" : {"ids" : [2]}
}
],
"timeMillis" : 1,
"counts" : {
"input" : 2,
"emit" : 4,
"reduce" : 1,
"output" : 3
},
"ok" : 1,
}

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

Is possible to query mongodb on array keys?

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}});