将MongoDB查询转换为Java [英] Convert MongoDB query into Java

查看:1023
本文介绍了将MongoDB查询转换为Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将以下mongo查询转换为java。

I need to convert the following mongo query into java.

db.sample.find( { name:"abc" }, { _id: 0, cities: { $elemMatch: { cityName: "A" }}});

我尝试了很多方法,但我找不到正确的方法。

I tried so many ways but I couldn't figure out the correct way.

    BasicDBObject eleMatch = new BasicDBObject();
    eleMatch.put("cityName","A");
    BasicDBObject up = new BasicDBObject();
    up.put("$elemMatch",eleMatch);
    BasicDBObject query = new BasicDBObject();
    query.put("name","abc");
    query.put("cities",up);
    DBCollection dbcoll = mongoTemplate.getCollection("sample");
    DBObject object = dbcoll.findOne(query);

但此对象的结果包含id。所以我只需要摆脱它。

But the result of this object contains the id . So i just need to get rid of that.

推荐答案

你需要提供检索字段作为findOne方法的第二个参数

You need to give retrieved fields as the second parameter of findOne method

BasicDBObject retrievedField = new BasicDBObject();
retrievedField.put("_id",0);

dbcoll.findOne(query, retrievedField);

此外,如果您想要检索您显示的确切查询,我认为您需要将elemMatch对象附加到retrieveFields而不是将其添加到queryObject。

Also if you want to retrieve the exact query you shown I think you need to append elemMatch object to retrievedFields instead of adding it to queryObject.

BasicDBObject eleMatch = new BasicDBObject();
eleMatch.put("cityName","A");
BasicDBObject up = new BasicDBObject();
up.put("$elemMatch",eleMatch);
retrievedField.append(up);

BasicDBObject query = new BasicDBObject();
query.put("name","abc");

DBCollection dbcoll = mongoTemplate.getCollection("sample");
DBObject object = dbcoll.findOne(query, retrievedField);

这篇关于将MongoDB查询转换为Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆