2

I am new to MongoDB and NoSQL and have the following query: I have the following documents in a sample MongoDB Collection

Data Collection

{ "Name" : "A",
  "date" : "2015-04-29"
},
{ "Name" : "B",
  "date" : "2015-04-29"
},
{ "Name" : "A",
  "date" : "2015-04-30"
}

I want to run a query on the comparing the dates trying to find out which name was not present on date = "2015-04-30" but was present on date = "2015-04-29".

The result of the above query would be :
{ "Name" : "B" }

Basically trying to compare results from two mongodb queries and then showing a result. Please let me know if this would be possible to do.

styvane
  • 59,869
  • 19
  • 150
  • 156
Jitesh
  • 114
  • 1
  • 7

3 Answers3

0

You can do that using aggregation pipeline operators. First you will need to group your document by Name using $group. The $push is a accumulator operator that let you create and array of date field. Use $match to field document with given criteria.

db.data.aggregate(
    [
        { "$group": { "_id": "$Name", "date": { "$push": "$date" }}},
        { "$match": { "date": { "$not": { "$all": ["2015-04-29", "2015-04-30" ]}}}}, 
    ]
)
styvane
  • 59,869
  • 19
  • 150
  • 156
0

I would achieve it with sets.

First take the elements that you are interested in: var need = db.a.distinct('Name', {date: '2015-04-29'})

take the element that you are not interested: var doNotNeed = db.a.distinct('Name', {date: '2015-04-30'})

Now if you subtract the set(need) with set(doNotNeed), you will get your answers. Mongoshell does not support sets, but you can use dictionaries:

var needSet = {}
for (var i=0; i < need.length; i++){
  needSet[need[i]] = 1;
}

for (var i=0; i < doNotNeed.length; i++){
  if (doNotNeed[i] in needSet){
     delete needSet[doNotNeed[i]]
  } 
}

needSet would have all the elements that satisfy your query. You can get them by calling Object.keys(needSet).

Community
  • 1
  • 1
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
0

I had similar issue, try this snippet

var arr=[];

db.Collection.find({"date":"2015-04-30"}).forEach(function(item){
var val=item.Name;

var found=db.Collection.findOne({"date":"2015-04-29","Name":val});

if (!found)
  arr.push(val);

});

printjson(arr);