How to query for MongoDB Document With duplicate Key? - mongodb

I am having Mongo Documents with duplicate Key,
{
"_id" : ObjectId("576a3b4a2bf2bc22bccb80ec"),
"Name" : "User1",
"Name" : "User2"
}
{
"_id" : ObjectId("576a3b4a2bf2bc22bccb80ab"),
"Name" : "User2",
"Name" : "User1"
}
When I try to query for Name as "User1". I always get one document only. But result should be two documents. Is there any way that I get correct result?
Thanks in advance
Note: I know my design is wrong I am just trying to make it success.

Please note that according to the docs, it IS possible to have duplicate key names, but depending on the driver you either might not be able to insert or read such data:
BSON documents may have more than one field with the same name. Most MongoDB interfaces, however, represent MongoDB with a structure (e.g. a hash table) that does not support duplicate field names. If you need to manipulate documents that have more than one field with the same name, see the driver documentation for your driver.
(Source: https://docs.mongodb.com/manual/core/document/#field-names)
Unfortunately, in order to correct your existing data, you will have to use a driver which can handle duplicate keys.

You cannot have two fields with same name in a collection in MongoDB .
When you try to insert a document with two fields with same key , MongoDB will update with the latest value rather than creating a separate fields.
Example :
db.test.insert({'Name':'user1','Name':'user2'})
db.test.insert({'Name':'user2','Name':'user1'})
Will result in inserting 2 documents as shown below
{ "_id" : ObjectId("576a8b4731157693143d0571"), "Name" : "user2" }
{ "_id" : ObjectId("576a8b5531157693143d0572"), "Name" : "user1" }

db.collection_name.find({"Name" : "User1"})

For a collection the ObjectId in MongoDB are unique because it acts as the primary key for that collection. As per the MongoDB Manual You can never have two documents in the same collection with same ObjectId.
But for different collections, there's a possibility of having the same ObjectID. And in that case while querying you obviously have to mention the collection name.
Hope this helps

Related

MongoDB - findOne by _id returns null in shell

When I run a simple findOne to get a document with no filter, I get this:
mongos> db.mycollection.findOne({},{_id:1})
{ "_id" : "1d0eb04fd0325cd79e4f8dc24268c6ad2205082199957ce42ffb9e802eec73c9" }
But when I feed that _id back in as a filter, I get no results:
mongos> db.mycollection.findOne({ "_id" : "1d0eb04fd0325cd79e4f8dc24268c6ad2205082199957ce42ffb9e802eec73c9" } )
null
Why is this? When I search on other fields I am able to get a result, but searching with _id returns nothing.
Of note is that these documents include a nested object with it's own _id. Searching using this nested._id field also returns nothing.
My environment: 2 shard mongoDB 3.4 running on Centos 7. Each replica set has 3 members and everything looks healthy.
Check MongoDB and make sure that your _id fields are all ObjectIds rather than plain strings. Basically when you inserting document with custom Id make sure you are passing object into "_id" field. For me the following would work ...
mongos> db.mycollection.findOne({},{_id:1})
{ "_id" : ObjectId("1d0eb04fd0325cd79e4f8dc24268c6ad2205082199957ce42ffb9e802eec73c9") }
and findOne by _id ...
mongos> db.mycollection.findOne({ "_id" : ObjectId("1d0eb04fd0325cd79e4f8dc24268c6ad2205082199957ce42ffb9e802eec73c9") } )
{ "_id" : ObjectId("1d0eb04fd0325cd79e4f8dc24268c6ad2205082199957ce42ffb9e802eec73c9"), "blahh" : "val"}
I found the issue- it turns out another user was running a 'remove()' command against the collection (we are just testing our application on this cluster at the moment). I believe that the documents that were being returned had been deleted by the time I ran the filtered 'findOne()'. Eventually the remove command completed and the collection was empty.

mongodb query on DBRef type

How do I turn this query in a valid mongodb Query in mongodb shell.
{ 'cars.owner.$ref' : 'users' }
cars.owner is a DBRef here, but $ref is invalid
I get this error:
"$err" : "Positional operator does not match the query specifier."
My objective here is to figure out if there are any cars "owned" by different collections then users.
You can query the DBRef in the Mongo shell, but you have to use the DBRef() function. The reference must include at least the $ref and $id. From the docs:
DBRef documents resemble the following document:
{ "$ref" : <value>, "$id" : <value>, "$db" : <value> }
When cars.owner is a reference to a document in the users collection, a query to find all cars where owner is a certain _id might look like (assuming both collections are in the same database):
db.cars.find({ "owner" : DBRef("users", ObjectId("<user _id value>")) })
The $ref and $id values cannot be queried directly. The DBRef is most useful in the case where there are multiple references to different collections in the same document. Using DBRef might be overkill when there is only one reference in the document, as others have mentioned.
If you need to reference different collections in your owners field, you are probably better served by using separate owner_collection and owner_id fields. The query to find all owners that are not users would then be a standard query:
db.cars.find({ owner_collection: { $ne: "users" } })
MongoDB documentation (database-reference) says following:
MongoDB applications use one of two methods for relating documents:
Manual references where you save the _id field of one document in another document as a reference. Then your application can run a second query to return the related data. These references are simple and sufficient for most use cases.
DBRefs are references from one document to another using the value of the first document’s _id field, collection name, and, optionally, its database name. By including these names, DBRefs allow documents located in multiple collections to be more easily linked with documents from a single collection. To resolve DBRefs, your application must perform additional queries to return the referenced documents. Many drivers have helper methods that form the query for the DBRef automatically. The drivers 1 do not automatically resolve DBRefs into documents.
I don't know about any plans, but I have read that DBRefs should be deprecated(?) nowadays. However, you can use fetch() -method to load referenced documents. For example, I have formView collection which stores documents that contains (DBRef) references to documents in formContent collection. So, running:
var view = db.formView.findOne()
view.formContent
view.formContent.fetch()
view.formContent.fetch().code
...Will result in following output:
DBRef("formContent", ObjectId("56cb155ea826872b67373e76"))
{
"_id" : ObjectId("56cb155ea826872b67373e76"),
"code" : "test_content",
"version" : 0
}
test_content
<parameterName>: DBRef("CollectionName", "_id Value")
put in collection.Then Create a Bean having feild name as parameterName, and put #Reference annotation of morphia orm then do operations you want

In Mongo is it possible to find documents with the same values for multiple fields?

I've been working with aggregates and can get it to work with one field but I cannot get i to work witht he use case in the title.
I have a collection of DVDs. I need to run a query that tries to identify duplicate DVDs based on three fields :
Heres an example document :
DVD
name : "Fargo",
director : "Cohen Brothers",
genre : "crime"
I want to use an aggregate that groups and returns documents whose three fields match but have been unable to do so. Is it even possible?
An example output based on similar functions, if there were 3 Fargos as above would be :
[['_id':'Fargo', 'size':3],['_id':'12 Angry Men', 'size':1] ]
I found the answer straight after asking the question :/
This has been already answered on S/O here :
Mongodb Aggregation Framework | Group over multiple values?
You can group by a Map as follows :
$group : {
_id : { name:'$name', director:'$director', genre:'$genre'}
}

MongoDB check the time of document log

I have a collection which stores a array of strings as a part of document and _id , is there a possibility that I can check the timestamp of any of the document which is logged.
the document structure is:
{ "_id" : NumberLong(1370891970), "k" : [ "argos","test"]}
Appreciate your help in advance.
-V
If this is your document structure, then there is no way to check it. None of your fields contains this information and you also overwrite your _id field.

MongoDB - DBRef to a DBObject

Using Java ... not that it matters.
Having a problem and maybe it is just a design issue.
I assign "_id" field to all of my documents, even embedded ones.
I have a parent document ( and the collection for those ) which has an embedded document
So I have something like:
{ "_id" : "49902cde5162504500b45c2c" ,
"name" : "MongoDB" ,
"type" : "database" ,
"count" : 1 ,
"info" : { "_id" : "49902cde5162504500b45c2y",
"x" : 203 ,
"y" : 102
}
}
Now I want to have another document which references my "info" via a DBRef, don't want a copy. So, I create a DBRef which points to the collection of the parent document and specifies the _id as xxxx5c2y. However, calling fetch() on the DBRef gives a NULL.
Does it mean that DBRef and fetch() only works on top level collection entry "_id" fields?
I would have expected that fetch() would consume all keys:values within the braces of the document .. but maybe that is asking too much. Does anyone know?? Is there no way to create cross document references except at the top level?
Thanks
Yes, your DBRef _id references need to be to documents in your collection, not to embedded documents.
If you want to find the embedded document you'll need to do a query on info._id and you'll need to add an index on that too (for performance) OR you'll need to store that embedded document in a collection and treat the embedded one as a copy. Copying is OK in MongoDB ... 'one fact one place' doesn't apply here ... provided you have some way to update the copy when the main one changes (eventual consistency).
BTW, on DBRef's, the official guidance says "Most developers only use DBRefs if the collection can change from one document to the next. If your referenced collection will always be the same, the manual references outlined above are more efficient."
Also, why do you want to reference info within a document? If it was an array I could understand why you might want to refer to individual entries but since it doesn't appear to be an array in your example, why not just refer to the containing document by its _id?