0

Using Mongo DB (Azure cosmos DB) and i need to filter out objects based on 2 fields inside the documents

Here is an example class:

class Event{
   public long startTime;
   public long endTime;
}

I need to find all events that their startTime==endTime

In sql i would do

Select * from Events where startTime=endTime
or
Select * from Events where startTime!=endTime

How do i do it in mongo?

collection.find(???).first();
Jay Gong
  • 23,163
  • 2
  • 27
  • 32
Maayan Hope
  • 1,482
  • 17
  • 32

1 Answers1

1

With native mongo filter operator,you could use find and aggregate to filter startTime==endTime :

find:

db.test.find({
    "$where": "this.fields1 == this.fields2"
});

aggregate:

db.test.aggregate([
    {
        $project:{
            fields1: 1,
            fields2: 1,
            difference: { $eq: ["$fields1", "$fields2"]}
        },
    },
    {
        $match: {
            difference: true
        },
    }
]);

However,based on the statements in official document:

The $where and the $eval operators are not supported by Azure Cosmos DB.

You could refer to the aggregation pipeline which is preview version.

Or you could try to use stored procedure to select the documents and loop it for comparing the filter columns,then return the desired data.(for reference packages :https://github.com/lmaccherone/documentdb-lumenize)

Jay Gong
  • 23,163
  • 2
  • 27
  • 32
  • What will be the Java version of it? AggregateIterable aggregate = collection.aggregate( Arrays.asList( Aggregates.project( Projections.fields( Projections.include("fSeen"), Projections.include("lSeen"), Projections.computed( "difference", Filters.eq("fSeen","lSeen") ) )) , Aggregates.match(Filters.eq("difference",true))) ); – Maayan Hope Jan 10 '19 at 08:13
  • @MaayanHope This is the code of java mongo db client package? – Jay Gong Jan 10 '19 at 08:17
  • com.mongodb.client.AggregateIterable – Maayan Hope Jan 10 '19 at 08:19
  • @MaayanHope I'm afraid that you can't treat cosmos db mongo api as normal mongo db, it just supports a subset of the MongoDB features. Please refer to my previous thread:https://stackoverflow.com/questions/52882764/cosmosdb-sql-api-vs-mongodb-api-which-one-to-use-for-my-scenario/52886759#52886759 – Jay Gong Jan 10 '19 at 08:23
  • @MaayanHope So,maybe you could try to use stored procedure as a workaround? Then execute the stored procedure in your java code. It could work. – Jay Gong Jan 10 '19 at 08:23