Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - Aggregate $match on ObjectId

I have a schema that looks like this:

var mongoose = require('mongoose');

module.exports = mongoose.model('Owner',{
    username: String,
    blocks: {type:mongoose.Schema.Types.ObjectId, ref: 'Block'},
});

I'm trying to run a query to see if Owner has a reference to Block's id. Owner has an array of ObjectIds. When I run db.owners.aggregate({$match: {username: 'example'}},{$unwind: "$blocks"},{$project: { _id : 1,blocks: 1}}) it returns:

{ "_id" : ObjectId("550d9dc64d9dc3d026fadfc7"), "blocks" : ObjectId("550dc117dc9605ab27070af7") }
{ "_id" : ObjectId("550d9dc64d9dc3d026fadfc7"), "blocks" : ObjectId("550dc123dc9605ab27070af8") }
{ "_id" : ObjectId("550d9dc64d9dc3d026fadfc7"), "blocks" : ObjectId("550dc12edc9605ab27070af9") }
{ "_id" : ObjectId("550d9dc64d9dc3d026fadfc7"), "blocks" : ObjectId("550dc157dc9605ab27070afa") }

How can I match the block id? I've tried db.publishers.aggregate({$match: {username: 'example'}},{$unwind: "$blocks"},{$project: { _id : 1,blocks: 1}},{$match : {"blocks._id" : '550dc157dc9605ab27070afa'}}) but that doesn't work.

like image 647
jordan Avatar asked Mar 21 '15 20:03

jordan


People also ask

What can the $match aggregation stage be used for?

The $match stage of the pipeline can be used to filter documents so that only ones meeting certain criteria move on to the next stage. In this article, we'll discuss the $match stage in more detail and provide examples that illustrate how to perform match aggregation in MongoDB.

What does $match do in MongoDB?

The MongoDB $match operator filters the documents to pass only those documents that match the specified condition(s) to the next pipeline stage.

Is aggregation slow in MongoDB?

Aggregation is slow - Working with Data - MongoDB Developer Community Forums.

Is aggregation fast in MongoDB?

On large collections of millions of documents, MongoDB's aggregation was shown to be much worse than Elasticsearch. Performance worsens with collection size when MongoDB starts using the disk due to limited system RAM. The $lookup stage used without indexes can be very slow.


1 Answers

I think you don't need aggreation for that, you can use a simple find() or findOne() query:

var Mongoose = require('mongoose');
var ObjectId = Mongoose.Types.ObjectId;

Owner.findOne({ username: 'example', blocks: new ObjectId('550dc157dc9605ab27070afa') }, function (err, owner) {
   ...
});
like image 132
Gergo Erdosi Avatar answered Sep 20 '22 14:09

Gergo Erdosi