Entity mode for the MongoDB integration
This week, we are launching a new entity mode for the MongoDB integration. This new mode gives you even more power by enabling you to insert and update existing entities that you previously inserted in Mongo.
Before you can try out entity mode, you need to update the MongoDB integration:
apibara plugins install sink-mongo
To enable entity mode, set the entityMode
option to true
. You must then
change your transform function to return a list of entity operations. These
operations are JSON objects that contain an entity
property that specifies
which entities need update and an update
property with a Mongo update
operation or
Mongo
pipeline
on that entity.
For example, the following update operation updates the owner of an NFT token and, at the same time, increases the transaction count on the same token.
export default function transform({ header, events }: Block) {const tokenIdCount = new Map<string, number>();const tokenIdToOwner = new Map<string, string>();for (const { event } of events) {const dest = event.data[1];const tokenId = uint256.uint256ToBN({low: event.data[2],high: event.data[3],});tokenIdToOwner.set(tokenId.toString(), dest);tokenIdCount.set(tokenId.toString(),(tokenIdCount.get(tokenId.toString()) ?? 0) + 1,);}return [...tokenIdToOwner.entries()].map(([tokenId, owner]) => ({entity: {tokenId,},update: {"$set": {tokenId,owner,updateAt: header?.timestamp,updateAtBlock: header?.blockNumber,},"$inc": {transferCount: tokenIdCount.get(tokenId) ?? 0,},},}));}
You can read more about entity mode, including details about its implementation, in our documentation. Looking forward to seeing what you're going to build with it!