MongoDB findOne query depends of result - mongodb

lets say that I have collection of something and record can look like that:
{
'_id' : MongoId('xxxxxx'),
'dir' : '/home/',
'category' : 'catname',
'someData' : 'very important info'
}
Is it possible to make only one query like collection.findOne({????}, {'someData' : 1}); to find colection matching this:
find by dir, if not found search for category name, if there is still
nothing find collection with category name is 'default'
or at least, can I say in this query that I want first match dir and if not found I want match category
collection.findOne({
$or : [
{'dir' : 'someCondition'},
{'category' : 'someCondition'}
]
});

Try this:
db.collection.aggregate([
{ '$project':
{
//Keep existing fields
'_id':1,
'dir':1,
'category':1,
'someData':1,
//Compute some new values
'sameDir': {'$eq':['$dir', 'SOMEDIR']},
'sameCategory': {'$eq':['$dir', 'SOMECATEGORY']},
'defaultCategory': {'$eq':['$dir', 'default']},
}
},
{ '$sort':
{
'sameDir': -1,
'sameCategory': -1,
'defaultCategory': -1,
}
},
{ '$limit': 1 }
])
The $sort will keep true values first, so a directory match will come first, followed by a category match, finally followed by a default category. The $limit:1 will keep the one on top (ie. the best match). Of course, make sure to input your own SOMEDIR and SOMECATEGORY values.

Related

Multiple $elemMatch in one query

My basic structure is this for a user:
{name : 'name',
lists : [
{id : 'xyz',
items : [
{name : 'itemName',
purchased : false
}
]
}]
}
I want to write a query where I can update itemName's purchased Bool.
I am able to get the list of items out using elemMatch, but I can't seem to select the item with the name of itemName.
Essentially, what I want is lists.$.gifts.$.purchased = true.
Is there a way to do this? It would be great if it could be done in one query, but if not, can it be done at all?
You cannot use multiple projection operator ($) in a query. The positional operator only supports one level nesting and also it matches the first element.
There is a JIRA ticket on this: https://jira.mongodb.org/browse/SERVER-831
In your case what you can do is do a find query to retrieve the document.
{
name : 'name',
lists : [
{
id : 'xyz',
items : [
{
name : 'itemName',
purchased : false
}
]
}
]
}
From the above json document, iterate the lists and items array to get the index of array element. From your document you can see like the array index is 0. You can then do a straight ahead update query of following form:
db.collection.update(
{name:'name'},
{$set:{'lists.0.items.0.purchased': true}}
)
or if you know the id in lists array, then you can fine tune the above query using positional operator,
db.collection.update(
{name:'name','lists.id':'xyz'},
{$set:{'lists.$.items.0.purchased': true}}
)
I hope this answers your question.

Query an array of embedded documents in mongodb

I'm having a little trouble writing a query that needs to compare a given value against a certain field in all embedded documents within an array. I will give an example to make the issue less abstract.
Let's say I want to use MongoDB to store the last queries that users on my network have entered into different online search engines. An entry in the collection would have a structure like this :
{
'_id' : 'zinfandel',
'last_search' : [
{
'engine' : 'google.com',
'query' : 'why is the sky blue'
},
{
'engine' : 'bing.com',
'query' : 'what is love'
},
{ 'engine' : 'yahoo.com',
'query' : 'how to tie a tie'
}
]
}
Now let's say user username enters a new query into a certain engine. The code that stores this query in the DB needs to find out whether there already exists an entry for the engine that the user used. If yes, this entry is to be updated with the new query. If not, a new entry should be created. My idea is to do a $push only if there is no entry for the given engine and do a $set otherwise. For this purpose, I tried to write my push like this :
db.mycollection.update(
{ '_id' : username , search.$.engine : { '$ne' : engine } },
{ '$push' : { 'search.$.engine' : engine, 'search.$.query' : query } }
)
However, this pushes a new embedded document even if there already was an entry for the given engine. The problem seems to be that the $ne operator doesn't work with arrays like I expect it to work. What I need is a way to make sure that not a single embedded document in the array has an "engine" entry that matches the specified engine.
Does anyone have an idea how to do that? Please tell me if I need to further clarify the question ...
You can push the item into the array with the following command:
db.mycollection.update({
_id: "zinfandel",
"last_search.engine": {
$nin: ["notwellknownengine.com"]
}
}, {
$push: {
"last_search": {
"engine" : "notwellknownengine.com",
"query" : "stackoveflow.com"
}
}
});

how to remove all documents from a collection except one in MongoDB

Is there any way to remove all the documents except one from a collection based on condition.
I am using MongoDB version 2.4.9
You can do this in below way,
db.inventory.remove( { type : "food" } )
Above query will remove documents with type equals to "food"
To remove document that not matches condition you can do,
db.inventory.remove( { type : { $ne: "food" } } )
or
db.inventory.remove( { type : { $nin: ["Apple", "Mango"] } } )
Check here for more info.
To remove all documents except one, we can use the query operator $nin (not in) over a specified array containing the values related to the documents that we want to keep.
db.collections.remove({"field_name":{$nin:["valueX"]}})
The advantage of $nin array is that we can use it to delete all documents except one or two or even many other documents.
To delete all documents except two:
db.collections.remove({"field_name":{$nin:["valueX", "valueY"]}})
To delete all documents except three:
db.collections.remove({"field_name":{$nin:["valueX", "valueY", "valueZ"]}})
Query
db.collection.remove({ "fieldName" : { $ne : "value"}})
As stated above by Taha EL BOUFFI, the following worked for me.
db.collection.remove({"fieldName" : { $nin: ["value"]}});

Use MongoDB aggregation to find set intersection of two sets within the same document

I'm trying to use the Mongo aggregation framework to find where there are records that have different unique sets within the same document. An example will best explain this:
Here is a document that is not my real data, but conceptually the same:
db.house.insert(
{
houseId : 123,
rooms: [{ name : 'bedroom',
owns : [
{name : 'bed'},
{name : 'cabinet'}
]},
{ name : 'kitchen',
owns : [
{name : 'sink'},
{name : 'cabinet'}
]}],
uses : [{name : 'sink'},
{name : 'cabinet'},
{name : 'bed'},
{name : 'sofa'}]
}
)
Notice that there are two hierarchies with similar items. It is also possible to use items that are not owned. I want to find documents like this one: where there is a house that uses something that it doesn't own.
So far I've built up the structure using the aggregate framework like below. This gets me to 2 sets of distinct items. However I haven't been able to find anything that could give me the result of a set intersection. Note that a simple count of set size will not work due to something like this: ['couch', 'cabinet'] compare to ['sofa', 'cabinet'].
{'$unwind':'$uses'}
{'$unwind':'$rooms'}
{'$unwind':'$rooms.owns'}
{'$group' : {_id:'$houseId',
use:{'$addToSet':'$uses.name'},
own:{'$addToSet':'$rooms.owns.name'}}}
produces:
{ _id : 123,
use : ['sink', 'cabinet', 'bed', 'sofa'],
own : ['bed', 'cabinet', 'sink']
}
How do I then find the set intersection of use and own in the next stage of the pipeline?
You were not very far from the full solution with aggregation framework - you needed one more thing before the $group step and that is something that would allow you to see if all the things that are being used match up with something that is owned.
Here is the full pipeline
> db.house.aggregate(
{'$unwind':'$uses'},
{'$unwind':'$rooms'},
{'$unwind':'$rooms.owns'},
{$project: { _id:0,
houseId:1,
uses:"$uses.name",
isOkay:{$cond:[{$eq:["$uses.name","$rooms.owns.name"]}, 1, 0]}
}
},
{$group: { _id:{house:"$houseId",item:"$uses"},
hasWhatHeUses:{$sum:"$isOkay"}
}
},
{$match:{hasWhatHeUses:0}})
and its output on your document
{
"result" : [
{
"_id" : {
"house" : 123,
"item" : "sofa"
},
"hasWhatHeUses" : 0
}
],
"ok" : 1
}
Explanation - once you unwrap both arrays you now want to flag the elements where used item is equal to owned item and give them a non-0 "score". Now when you regroup things back by houseId you can check if any used items didn't get a match. Using 1 and 0 for score allows you to do a sum and now a match for item which has sum 0 means it was used but didn't match anything in "owned". Hope you enjoyed this!
So here is a solution not using the aggregation framework. This uses the $where operator and javascript. This feels much more clunky to me, but it seems to work so I wanted to put it out there if anyone else comes across this question.
db.houses.find({'$where':
function() {
var ownSet = {};
var useSet = {};
for (var i=0;i<obj.uses.length;i++){
useSet[obj.uses[i].name] = true;
}
for (var i=0;i<obj.rooms.length;i++){
var room = obj.rooms[i];
for (var j=0;j<room.owns.length;j++){
ownSet[room.owns[j].name] = true;
}
}
for (var prop in ownSet) {
if (ownSet.hasOwnProperty(prop)) {
if (!useSet[prop]){
return true;
}
}
}
for (var prop in useSet) {
if (useSet.hasOwnProperty(prop)) {
if (!ownSet[prop]){
return true;
}
}
}
return false
}
})
For MongoDB 2.6+ Only
As of MongoDB 2.6, there are set operations available in the project pipeline stage. The way to answer this problem with the new operations is:
db.house.aggregate([
{'$unwind':'$uses'},
{'$unwind':'$rooms'},
{'$unwind':'$rooms.owns'},
{'$group' : {_id:'$houseId',
use:{'$addToSet':'$uses.name'},
own:{'$addToSet':'$rooms.owns.name'}}},
{'$project': {int:{$setIntersection:["$use","$own"]}}}
]);

mongodb: inc high level document and embedded document

I want to increment two values, one in high level document and one in embedded document:
{
studentId: "x1"
numberOfAttending: 2
courses: [
{
courseId:"y1"
numberOfAttending: 1
},
{
courseId:"y2"
numberOfAttending: 1
}
]
}
How could i inc the number of attending for student and for the course (upsert). and could i do it with a single update query ?
That's going to be tough since courses is an array. You'll need to know the index of the course you want to update, then do something like:
{ '$inc' : {numberOfAttending : 1, 'courses.1.numberOfAttending' : 1}}
Have you thought about switching it to a single embedded doc with courseId as a key for each course? If so, you can run a command like this to increment both. This doesn't depend on position so it's going to be less fragile:
{ '$inc' : { numberOfAttending : 1, 'courses.y2.numberOfAttending' : 1}}