Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find mongo documents with a same field

Tags:

mongodb

I have a mongo collection, and I need to find documents in this collection, in which fields name and address are equal.

I have searched a lot, I could only find MongoDb query condition on comparing 2 fields and MongoDB: Unique and sparse compound indexes with sparse values, but in these questions they are looking for documents in which field a = field b, but I need to find document1.a == document2.a

like image 444
Nikita Platonenko Avatar asked Feb 08 '13 10:02

Nikita Platonenko


People also ask

How do I find a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

What is the Mongo command to find all documents that match search criteria?

To find documents that match a set of selection criteria, call find() with the <criteria> parameter. MongoDB provides various query operators to specify the criteria.

How do I search multiple documents in MongoDB?

You can query for multiple documents in a collection with collection. find() . The find() method uses a query document that you provide to match the subset of the documents in the collection that match the query.


1 Answers

You can find duplicates using the Aggregation Framework and $group.

Example data set up:

// Batch insert some test data db.mycollection.insert([     {a:1, b:2, c:3},     {a:1, b:2, c:4},     {a:0, b:2, c:3},     {a:3, b:2, c:4} ]) 

Aggregation query:

db.mycollection.aggregate(     { $group: {          // Group by fields to match on (a,b)         _id: { a: "$a", b: "$b" },          // Count number of matching docs for the group         count: { $sum:  1 },          // Save the _id for matching docs         docs: { $push: "$_id" }     }},      // Limit results to duplicates (more than 1 match)      { $match: {         count: { $gt : 1 }     }} ) 

Example output:

{     "result" : [         {             "_id" : {                 "a" : 1,                 "b" : 2             },             "count" : 2,             "docs" : [                 ObjectId("5162b2e7d650a687b2154232"),                 ObjectId("5162b2e7d650a687b2154233")             ]         }     ],     "ok" : 1 } 
like image 129
Stennie Avatar answered Sep 20 '22 11:09

Stennie