简体   繁体   中英

mongodb compare two different fields using java driver

this is the data i have inserted.

{"_id" : ObjectId("4f97ebb5429c822f0506d9d8"), "direction" : "out", "status" : "complete",  "inputfile" : "data",  "messageid" :"mid_1","previousmessageid" : "previd_1"}
{"_id" : ObjectId("4f97ebb5429c822f0506d9d8"), "direction" : "in", "status" : "complete",  "inputfile" : "data1",  "messageid" :"0","previousmessageid" : "mid_1"}

Now i have to query the db and find the records matching the messageid in the first record with direction "in" and previousmessageid with direction "out" in the second record. I have a huge volume of data.Kindly suggest me a best method fetch the records. thanks in advance.

The easiest thing to do will be to make two queries:

  1. Query for the "first record" according to whatever criteria you want to find that record.
  2. Once you have the "first record", you can use its messageid and the direction "out" to find the second set of records.

Here's an example using the MongoDB shell, though you can convert this fairly trivially to any language:

> var firstRecord = db.collection.findOne({direction: "in", /* other criteria */})
> var cursor = db.collection.find({previousmessageid: firstRecord["messageid"], direction: "out"})

This will be efficient assuming you have an index to serve the first query, and an index on {previousmessageid: 1, direction: 1} .

EDIT: Since you are dealing with multiple records with direction "in", you can adjust this technique slightly to work:

> var inRecords = db.collection.find({direction: "in", /* other critiera */})
> var messageIds = []
> inRecords.forEach(function (record) { messageIds[messageIds.length] = record.messageid })
> var cursor = db.collection.find({direction: "out", previousmessageid: {$in: messageIds}})
> cursor.sort({previousmessageid: 1})
> /* do something with cursor */

You can then process the full set of replies to all the messages in your application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM