I'm using spring data mongodb in my application. It uses mongodb 2.6. I want to query documents of a collection by the id which mongo assigns during insertion. I'm doing something like this:
Query query = new Query();
String id = "542385a91f00bf7dbeae1fc7";
query.addCriteria(Criteria.where("_id").new Object(id));
template.find(query, entity.class);
This query translates to:
{ "_id" : { "$oid" : "542385a91f00bf7dbeae1fc7"}}
When I execute the same on mongo shell, it gives an error:
error: {
"$err" : "Can't canonicalize query: BadValue unknown operator: $oid",
"code" : 17287
}
How do I query by id using spring data mongodb?
It should read
new ObjectId(id)
instead of new Object(id). Please see the API docs for details.
Related
I have a collection in mongodb which has many documents. Using Studio 3T I can see the document looks like below
{
"DialectType" : "ORACLE",
"DomainName" : "NewDomain"
}
There are many of this type with different values but with same keys. I am using below code to query the documents-
Query query = Query.query(Criteria.where("DialectType").is("ORACLE"));
mongoOperations.find(query, DialectTypeCollection.class, "my_collection_name");
The above query does not return records. I am not sure what is the issue. Any help is appreciated.
I have a collection in mongo which contains 6 documents .When I run query directly in mongo it is qorking fine.But when I run the same query in spring , I am not getting the result
I have the following query
Mongo DB: db.getCollection('table_name').find({"column_1" : "value_1" })
Spring :
Query q = new BasicQuery("{ column_1: 'value_1'}");
this.mongoOps.find(q, TableName.class, "table_name");
I tried with different mongo versions ans with different spring versions but not working.What might be the issue here.
NOTE:Query is working with JDBC as well
Thanks in advance...
If you're considerating use Query class, try add Criteria
Query query = new Query();
query.addCriteria(Criteria.where("field_1").in("value_1"));
Edit
If you want to use BasicQuery, try:
BasicQuery query1 = new BasicQuery("{ 'field': 'value_1' }");
User userTest1 = mongoOperation.findOne(query1, YourClass.class);
Remember in Mongo we don't call column to fields, because it doesn't has column :)
There I am stuck, how to remove embedded document in mongodb. I am using spring data mongodb criteria, I am doing it like the following:
// database
"_id" : ObjectId("55683d51e4b0b6050c5b0db7"),
"_class" : "com.samepinch.domain.metadata.Metadata",
"preferenceType" : "SHOPPING",
"subtypes" : [
{
"_id" : ObjectId("55683d51e4b0b6050c5b0db6"),
"leftValue" : "VEG",
"rightValue" : "NON_VEG",
"preferencePoint" : 0
}
],
"createdDate" : ISODate("2015-05-29T10:20:01.610Z"),
"updatedDate" : ISODate("2015-05-29T10:20:01.610Z")
// query
mongoTemplate.updateMulti(new Query(),
new Update().pull("subtypes", Query.query(Criteria.where("subtypes._id").is(new objectId("55683d51e4b0b6050c5b0db6"))),Metadata.class);
What i am doing wrong?
Thanks in advance!
subtypes is in nested objects so you should first pass this in $elemMatch is matched first matching array elements of given conditions. Update query as :
db.updateMulti.update({"subtypes":{"$elemMatch":{"_id":ObjectId("55683d51e4b0b6050c5b0db6")}}},
{"$pull":{"subtypes":{"_id":ObjectId("55683d51e4b0b6050c5b0db6")}}})
this query pull exact matching array elements from subtypes array .
And with the help of this spring elemMatch ( not that much expertise in spring mongo ) I converted this query in spring format as below :
mongoTemplate.updateMulti(new Query(
where("subtypes").elemMatch(where("_id").is(ew objectId("55683d51e4b0b6050c5b0db6"))).pull(
pull("subtypes", Query.query(Criteria.where("_id").is(new objectId("55683d51e4b0b6050c5b0db6"))),Metadata.class
));
this above spring query not tested I hope you will convert mongo update query in spring mongo query format.
So I am trying to do a mongodb query using Spring data with limit attached. I have noticed that Spring data doesn't add limit to the query itself, but rather gets all data, performs limit on it on Java side then returns limited result. Is this true or am I doing something wrong in my code here.
Criteria criteria = queryBuilder.getQuery(searchCriteria);
Query query = new Query(criteria);
query.limit(500);
logger.Debug("Query: " + query);
if (query.getQueryObject() != null){
resultSet = (List<T>) _mongoDb.find(query, model.getClass(), _collectionName);
}
The query I see in the log is this:
Query: Query: { "$or" : [ { "PARTY" : { "$elemMatch" : { "PARTY_ID" : "32135"}}} , { "ABBR_NUM" : "6873"} , { "ANN_ABBR_NUM" : "6873"}]}, Fields: null, Sort: null
I don't see a limit of 500 attached to this query. Is there something I have missed? By the way, the fields in the query are part of "searchCriteria" passed in.
Your log statement is just logging the query. Behind the scenes the limit actually gets applied to the cursor, so you're not going to see it using that log statement.
Try using the MongoDB profiler (set profile level 2) then query the system.profile collection and you will see that your limit is actually applied to the query, indicated by the ntoreturn field in the profile record.
I'm testing out spring-data and it's mongodb support.
I have a question about the query creation when using or-queries. Consider the following:
Query query = new Query().or(new Query(where("receiverId").is(userId)), new Query(where("requesterId").is(userId)));
query.and(where("status").is(status));
This will result in the following mongodb query:
"$or" : [ { "receiverId" : { "$oid" : "4d78696025d0d46b42d9c579"}} , { "requesterId" : { "$oid" : "4d78696025d0d46b42d9c579"}}] , "status" : "REQUESTED"}
This returns zero results while one is expected. Running this query in mongodb command results in following error:
error: { "$err" : "invalid operator: $oid", "code" : 10068 }
Modifying the query and running it in mongodb command works fine:
{ "$or" : [ { "receiverId" : ObjectId("4d78696025d0d46b42d9c579")} , { "requesterId" : ObjectId("4d78696025d0d46b42d9c579")}] , "status" : "REQUESTED"}
Notice the use of ObjectId("...") instead of $oid.
Am I going about something the wrong way? Maybe setting up the query wrong?
Are you inspecting that query variable at runtime or is that what you are seeing in MongoDB's logs?
Int he C# driver, if you inspect the query variable, you see $oid as well, but that is not the actual query that is sent to the server. At some point, it changes that to a valid MongoDB query.
If you are running on linux, you may want to start up mongosniff which will show you realtime queries, updates and inserts as they happen. If you are on Windows, you should start up mongod.exe with -vvvv flag which will enable it to log every query, update, insert, or command to the log file.
Then you can actually see the exact query that is being submitted.